标签:
网上找了一大堆的例子,没一个跑通的,都是copy转发,哎,整理得好辛苦。。做个笔记,方便正遇到此问题的猿们能够得到帮助。。。。废话不多说,贴代码。。。。。
项目结构说明:
1.dao层的admin、website包中包含的Mapper.xml文件分别操作不同的数据库
2.举例:192.168.1.1下有个mysql数据库叫 odao_admin
192.168.1.2下有个sqlserver数据库叫 odao_mobile
详情见下方的jdbc.properties文件
1:Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.odao.official</groupId> <artifactId>odao-official</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>odao-official website</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.2.4.RELEASE</spring.version> <jackson.version>2.5.0</jackson.version> </properties> <dependencies> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- activemq --> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-all</artifactId> <version>5.9.0</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>5.9.0</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.apache.xbean</groupId> <artifactId>xbean-spring</artifactId> <version>4.2</version> </dependency> <!-- mybatis 包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!--mybatis spring 插件 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.12</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.4</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- servlet <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- json --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- 文件上传 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!-- ORM映射持久化 --> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0.2</version> </dependency> <!-- sqlserver驱动 --> <dependency> <groupId>com.hynnet</groupId> <artifactId>sqljdbc4-chs</artifactId> <version>4.0.2206.100</version> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <!-- atomikos --> <dependency> <groupId>com.atomikos</groupId> <artifactId>transactions-jdbc</artifactId> <version>3.9.3</version> </dependency> <!-- cglib --> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>3.2.2</version> </dependency> </dependencies> </project>
2:web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <display-name>odao-official</display-name> <!-- Spring Application Context Listener & spring-mybaits --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring MVC Config --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- Filter all resources --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Log4J --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <!-- Spring Log4J config --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- Spring 编码过滤器 --> <filter> <filter-name>characterEncoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
3:spring-mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd "> <!--引入配置属性文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 自动扫描 --> <context:component-scan base-package="com.odao" /> <bean id="abstractXADataSource" class="com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean" init-method="init" destroy-method="close" abstract="true"> <property name="xaDataSourceClassName" value="com.mysql.jdbc.Driver"/> <property name="poolSize" value="10" /> <property name="minPoolSize" value="10"/> <property name="maxPoolSize" value="30"/> <property name="borrowConnectionTimeout" value="60"/> <property name="reapTimeout" value="20"/> <!-- 最大空闲时间 --> <property name="maxIdleTime" value="60"/> <property name="maintenanceInterval" value="60"/> <property name="loginTimeout" value="60"/> <property name="testQuery"> <value>select 1</value> </property> </bean> <!-- 配置连接odao_mobile库的数据源 --> <bean id="odaoMobile" class="com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean"> <!-- value只要两个数据源不同就行,随便取名 --> <property name="uniqueResourceName" value="odaoMobileDB" /> <property name="driverClassName"> <value>${odaoMobile.jdbc.driver}</value> </property> <property name="url"> <value>${odaoMobile.jdbc.url}</value> </property> <property name="user"> <value>${odaoMobile.jdbc.username}</value> </property> <property name="password"> <value>${odaoMobile.jdbc.password}</value> </property> </bean> <!-- 配置连接odao_admin库的数据源 --> <bean id="odaoAdmin" class="com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean"> <!-- value只要两个数据源不同就行,随便取名 --> <property name="uniqueResourceName" value="odaoAdminDB" /> <property name="driverClassName"> <value>${odaoAdmin.jdbc.driver}</value> </property> <property name="url"> <value>${odaoAdmin.jdbc.url}</value> </property> <property name="user"> <value>${odaoAdmin.jdbc.usernam}</value> </property> <property name="password"> <value>${odaoAdmin.jdbc.password}</value> </property> </bean> <bean id="webSiteSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="odaoMobile" /> <property name="mapperLocations" value="classpath:com/odao/dao/website/**/impl/*Mapper.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.odao.dao.website" /> <property name="sqlSessionFactoryBeanName" value="webSiteSqlSessionFactory" /> </bean> <bean id="adminSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="odaoAdmin" /> <property name="mapperLocations" value="classpath:com/odao/dao/admin/**/impl/*Mapper.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.odao.dao.admin" /> <property name="sqlSessionFactoryBeanName" value="adminSqlSessionFactory" /> </bean> <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close"> <property name="forceShutdown"> <value>true</value> </property> </bean> <bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp"> <property name="transactionTimeout" value="300" /> </bean> <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="transactionManager"> <ref bean="atomikosTransactionManager"/> </property> <property name="userTransaction"> <ref bean="atomikosUserTransaction"/> </property> <!-- 必须设置,否则程序出现异常 JtaTransactionManager does not support custom isolation levels by default --> <property name="allowCustomIsolationLevels" value="true"/> </bean> <aop:config proxy-target-class="true"> <aop:advisor pointcut="execution(* *com.odao.service..*(..))" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="springTransactionManager"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="has*" propagation="REQUIRED" read-only="true" /> <tx:method name="locate*" propagation="REQUIRED" read-only="true" /> <tx:method name="register*" propagation="REQUIRED" rollback-for="java.lang.Exception" /> </tx:attributes> </tx:advice> </beans>
注意:上面配置的basePackage属性指定的不同的Mapper文件
4:spring-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.odao.controller" /> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- json转换器 --> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 配置多文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <!-- 上传文件大小限制为31M,31*1024*1024 --> <value>32505856</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> </beans>
5. jdbc.properties:
#mysql数据库链接
odaoAdmin.jdbc.driver=com.mysql.jdbc.Driver odaoAdmin.jdbc.url=jdbc:mysql://192.168.1.1:3306/odao_admin?useUnicode=true&characterEncoding=utf8 odaoAdmin.jdbc.username=odao odaoAdmin.jdbc.password=whattime
#sqlserver数据库链接 odaoMobile.jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver odaoMobile.jdbc.url=jdbc:sqlserver://192.168.1.2:1433;DatabaseName=odao_mobile odaoMobile.jdbc.username=sa odaoMobile.jdbc.password=odao
validationQuery=SELECT 1
6.jta.properties:
com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory com.atomikos.icatch.console_file_name = tm.out com.atomikos.icatch.log_base_name = tmlog com.atomikos.icatch.tm_unique_name = com.atomikos.spring.jdbc.tm com.atomikos.icatch.console_log_level =INFO
注意:jta.properties 文件在你复制的时候可能有空格,记得删掉
7:log4j.properties:
### set log levels ### log4j.rootLogger = Debug , C , D , E ### console ### log4j.appender.C = org.apache.log4j.ConsoleAppender log4j.appender.C.Target = System.out log4j.appender.C.layout = org.apache.log4j.PatternLayout log4j.appender.C.layout.ConversionPattern = [springmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH\:mm\:ss}] %C.%M(%L) | %m%n ### log file ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = ../logs/springmvc-mybatis-demo.log log4j.appender.D.Append = true log4j.appender.D.Threshold = INFO log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = [springmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH\:mm\:ss}] %C.%M(%L) | %m%n ### exception ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File = ../logs/springmvc-mybatis-demo_error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern =[sspringmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH\:mm\:ss}] %C.%M(%L) | %m%n
8. 控制层 UserInfoController.java :
package com.odao.controller.user; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.odao.entity.UserInfo; import com.odao.service.website.UserService; @Controller @RequestMapping("/user/") public class UserInfoController { @Autowired private UserService userService; @RequestMapping("userInfoList.do") public ModelAndView getUserInfoList(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView = new ModelAndView("user/userInfoList"); List<UserInfo> userInfoList = userService.selectAll(); List<UserInfo> userInfo = userService.selectUser(); modelAndView.addObject("userName",userInfoList.get(0).getTest_id()+"===="+userInfo.get(0).getTest_name()); return modelAndView; } @ResponseBody @RequestMapping("updateUserInfo.do") public ModelAndView updateUserInfo(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView = new ModelAndView("user/userInfoList"); UserInfo user = new UserInfo(); user.setTest_id(1); user.setTest_name("嗯~有耐心看到这里的都帅");; userService.saveUser(user); return modelAndView; } }
9.业务逻辑层:UserService.java:
package com.odao.service.website; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.odao.dao.admin.user.AdminUserInfoDao; import com.odao.dao.website.user.WebSiteUserInfoDao; import com.odao.entity.UserInfo; @Service public class UserService { @Autowired private WebSiteUserInfoDao websiteUserInfoDao; @Autowired private AdminUserInfoDao adminUserInfoDao; public List<UserInfo> selectAll() { return websiteUserInfoDao.selectAll(); } public List<UserInfo> selectUser() { return adminUserInfoDao.selectUser(); }
public void saveUser(UserInfo userInfo){ websiteUserInfoDao.saveUser(userInfo);
//测试操作不同数据库时,事物回滚的一致性(要么都成功,要么都失败)
if(1==1){
throw new NullPointerException();
} adminUserInfoDao.saveUser(userInfo); } }
整个项目大致就这样,entity跟dao就不贴了,你们看方法也能猜到,图片上的transaction-context.xml文件内容我给弄到了spring-mybatis.xml里面,就是一些关于分布式事物的
有什么不明白的q我:370624997(好久不见)
码字不容易,转载请注明出处,谢谢。。。。。
Spring+Mybatis+SpringMVC+Atomikos多数据源共存+分布式事物处理
标签:
原文地址:http://www.cnblogs.com/wangfajun/p/5455687.html