• Spring整合MyBaytis


    1、准备jar包

    A、第一种方式:配置SqlSessionFactoryBean+配置SqlSessionTemplate

    a、项目结构

    b、applicationContext.xml  带详细注释

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     4     xmlns:p="http://www.springframework.org/schema/p"
     5     xmlns:aop="http://www.springframework.org/schema/aop" 
     6     xmlns:tx="http://www.springframework.org/schema/tx"
     7     xsi:schemaLocation="http://www.springframework.org/schema/beans
     8     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
     9     http://www.springframework.org/schema/aop
    10     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    11     http://www.springframework.org/schema/tx
    12     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    13 
    14     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    15         destroy-method="close">
    16         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    17         <!-- <property name="url">
    18             <value><![CDATA[jdbc:mysql://127.0.0.1:3306/smbms?
    19                     useUnicode=true&characterEncoding=utf-8]]></value>
    20         </property> -->
    21         <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
    22                         useUnicode=true&amp;characterEncoding=utf-8" />
    23         <property name="username" value="root" />
    24         <property name="password" value="root" />
    25     </bean>
    26 
    27     <!-- 配置SqlSessionFactoryBean --><!-- 为整合应用提供SqlSession对象资源 -->
    28     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    29         <!-- 引用数据源组件 -->
    30         <property name="dataSource" ref="dataSource" />
    31         <!-- 引用MyBatis配置文件中的配置 -->
    32         <property name="configLocation" value="classpath:mybatis-config.xml" />
    33         <!-- 配置SQL映射文件信息 -->
    34         <property name="mapperLocations">
    35             <list>
    36                 <value>classpath:cn/smbms/dao/*/*.xml</value><!-- 映射文件    之前在mybatis配置文件中-->
    37             </list>
    38         </property>
    39     </bean>
    40     
    41     <!-- 配置SqlSessionTemplate --><!-- 负责管理MyBatis的SqlSession,调用SQL映射语句,实现对数据库的访问-->
    42     <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    43         <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /><!-- 整合好的对象资源赋值给SqlSessionTemplate -->
    44     </bean>
    45     <!-- 配置DAO -->
    46     <bean id="userMapper" class="cn.smbms.dao.user.UserMapperImpl"><!-- Dao层声明的对象是SqlSessionTemplate来获得SqlSession -->
    47         <property name="sqlSession" ref="sqlSessionTemplate" /><!-- 把管理的SqlSession赋值给Dao层set方法 -->
    48     </bean>
    49     <!-- 配置业务Bean -->
    50     <bean id="userService" class="cn.smbms.service.user.UserServiceImpl">
    51         <property name="userMapper" ref="userMapper" /><!-- 把Dao层对象赋值给Server层set方法 -->
    52     </bean>
    53 </beans>
    View Code

    c、mybatis-config.xml

    1 <?xml version="1.0" encoding="UTF-8" ?>
    2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    3     "http://mybatis.org/dtd/mybatis-3-config.dtd">
    4 <configuration>
    5     <!--类型别名 -->
    6     <typeAliases>
    7         <package name="cn.smbms.pojo" />
    8     </typeAliases>
    9 </configuration>
    View Code

    d、log4j

     1 log4j.rootLogger=DEBUG,CONSOLE,file
     2 #log4j.rootLogger=ERROR,ROLLING_FILE
     3 log4j.logger.cn.smbms.dao=debug
     4 log4j.logger.com.ibatis=debug 
     5 log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
     6 log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
     7 log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
     8 log4j.logger.java.sql.Connection=debug 
     9 log4j.logger.java.sql.Statement=debug 
    10 log4j.logger.java.sql.PreparedStatement=debug 
    11 log4j.logger.java.sql.ResultSet=debug 
    12 log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
    13 
    14 ######################################################################################
    15 # Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
    16 ######################################################################################
    17 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    18 log4j.appender.Threshold=error
    19 log4j.appender.CONSOLE.Target=System.out
    20 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    21 log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
    22 
    23 
    24 ######################################################################################
    25 # DailyRolling File  \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
    26 ######################################################################################
    27 log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
    28 log4j.appender.file.DatePattern=yyyy-MM-dd
    29 log4j.appender.file.File=log.log
    30 log4j.appender.file.Append=true
    31 log4j.appender.file.Threshold=error
    32 log4j.appender.file.layout=org.apache.log4j.PatternLayout
    33 log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
    34 
    35 
    36 log4j.logger.com.opensymphony.xwork2=error  
    View Code

    e、UserMapper.java

     1 package cn.smbms.dao.user;
     2 
     3 import java.util.List;
     4 import cn.smbms.pojo.User;
     5 
     6 public interface UserMapper {
     7     /**
     8      * 查询用户列表(参数:对象入参)
     9      * @return
    10      */
    11     public List<User> getUserList(User user);
    12 }
    View Code

    f、UserMapperImpl.java

     1 package cn.smbms.dao.user;
     2 
     3 import java.util.List;
     4 import org.apache.ibatis.session.SqlSession;
     5 import org.mybatis.spring.SqlSessionTemplate;
     6 
     7 import cn.smbms.pojo.User;
     8 
     9 public class UserMapperImpl implements UserMapper {
    10     private SqlSessionTemplate sqlSession;
    11 
    12     @Override
    13     public List<User> getUserList(User user) {
    14         return sqlSession.selectList(
    15                 "cn.smbms.dao.user.UserMapper.getUserList", user);
    16     }
    17 
    18     public SqlSessionTemplate getSqlSession() {
    19         return sqlSession;
    20     }
    21 
    22     public void setSqlSession(SqlSessionTemplate sqlSession) {
    23         this.sqlSession = sqlSession;
    24     }
    25 
    26 }
    View Code

    g、UserMapper.xml

     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     3     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     4 <mapper namespace="cn.smbms.dao.user.UserMapper">
     5     <!-- 当数据库中的字段信息与对象的属性不一致时需要通过resultMap来映射 -->
     6     <resultMap type="User" id="userList">
     7         <!-- <result property="id" column="id" />
     8         <result property="userCode" column="userCode" />
     9         <result property="userName" column="userName" />
    10         <result property="phone" column="phone" />
    11         <result property="birthday" column="birthday" />
    12         <result property="gender" column="gender" />
    13         <result property="userRole" column="userRole" /> -->
    14         <result property="userRoleName" column="roleName" />
    15     </resultMap>
    16     <!-- 查询用户列表(参数:对象入参) -->
    17     <select id="getUserList" resultMap="userList" parameterType="User">
    18         select u.*,r.roleName from smbms_user u,smbms_role r
    19         where u.userName like CONCAT ('%',#{userName},'%')
    20         and u.userRole = #{userRole} and u.userRole = r.id
    21     </select>
    22 </mapper>
    View Code

    h、User.java

      1 package cn.smbms.pojo;
      2 
      3 import java.util.Date;
      4 
      5 public class User {
      6     private Integer id;           // id
      7     private String  userCode;     // 用户编码
      8     private String  userName;     // 用户名称
      9     private String  userPassword; // 用户密码
     10     private Integer gender;       // 性别
     11     private Date    birthday;     // 出生日期
     12     private String  phone;        // 电话
     13     private String  address;      // 地址
     14     private Integer userRole;     // 用户角色ID
     15     private Integer createdBy;    // 创建者
     16     private Date    creationDate; // 创建时间
     17     private Integer modifyBy;     // 更新者
     18     private Date    modifyDate;   // 更新时间
     19     private String  userRoleName; // 用户角色名称
     20 
     21     public Integer getId() {
     22         return id;
     23     }
     24 
     25     public void setId(Integer id) {
     26         this.id = id;
     27     }
     28 
     29     public String getUserCode() {
     30         return userCode;
     31     }
     32 
     33     public void setUserCode(String userCode) {
     34         this.userCode = userCode;
     35     }
     36 
     37     public String getUserName() {
     38         return userName;
     39     }
     40 
     41     public void setUserName(String userName) {
     42         this.userName = userName;
     43     }
     44 
     45     public String getUserPassword() {
     46         return userPassword;
     47     }
     48 
     49     public void setUserPassword(String userPassword) {
     50         this.userPassword = userPassword;
     51     }
     52 
     53     public Integer getGender() {
     54         return gender;
     55     }
     56 
     57     public void setGender(Integer gender) {
     58         this.gender = gender;
     59     }
     60 
     61     public Date getBirthday() {
     62         return birthday;
     63     }
     64 
     65     public void setBirthday(Date birthday) {
     66         this.birthday = birthday;
     67     }
     68 
     69     public String getPhone() {
     70         return phone;
     71     }
     72 
     73     public void setPhone(String phone) {
     74         this.phone = phone;
     75     }
     76 
     77     public String getAddress() {
     78         return address;
     79     }
     80 
     81     public void setAddress(String address) {
     82         this.address = address;
     83     }
     84 
     85     public Integer getUserRole() {
     86         return userRole;
     87     }
     88 
     89     public void setUserRole(Integer userRole) {
     90         this.userRole = userRole;
     91     }
     92 
     93     public Integer getCreatedBy() {
     94         return createdBy;
     95     }
     96 
     97     public void setCreatedBy(Integer createdBy) {
     98         this.createdBy = createdBy;
     99     }
    100 
    101     public Date getCreationDate() {
    102         return creationDate;
    103     }
    104 
    105     public void setCreationDate(Date creationDate) {
    106         this.creationDate = creationDate;
    107     }
    108 
    109     public Integer getModifyBy() {
    110         return modifyBy;
    111     }
    112 
    113     public void setModifyBy(Integer modifyBy) {
    114         this.modifyBy = modifyBy;
    115     }
    116 
    117     public Date getModifyDate() {
    118         return modifyDate;
    119     }
    120 
    121     public void setModifyDate(Date modifyDate) {
    122         this.modifyDate = modifyDate;
    123     }
    124 
    125     public String getUserRoleName() {
    126         return userRoleName;
    127     }
    128 
    129     public void setUserRoleName(String userRoleName) {
    130         this.userRoleName = userRoleName;
    131     }
    132 }
    View Code

    i、UserService.java

    1 package cn.smbms.service.user;
    2 
    3 import java.util.List;
    4 import cn.smbms.pojo.User;
    5 
    6 public interface UserService {
    7     public List<User> findUsersWithConditions(User user);
    8 }
    View Code

    J、UserServiceImpl.java

     1 package cn.smbms.service.user;
     2 
     3 import java.util.List;
     4 
     5 import cn.smbms.dao.user.UserMapper;
     6 import cn.smbms.pojo.User;
     7 
     8 public class UserServiceImpl implements UserService {
     9     private UserMapper userMapper;
    10 
    11     @Override
    12     public List<User> findUsersWithConditions(User user) {
    13         try {
    14             return userMapper.getUserList(user);
    15         } catch (RuntimeException e) {
    16             e.printStackTrace();
    17             throw e;
    18         }
    19     }
    20 
    21     public UserMapper getUserMapper() {
    22         return userMapper;
    23     }
    24 
    25     public void setUserMapper(UserMapper userMapper) {
    26         this.userMapper = userMapper;
    27     }
    28 
    29 }
    View Code

    k、test

     1 package cn.smbms.test.user;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 import org.apache.log4j.Logger;
     7 import org.junit.Before;
     8 import org.junit.Test;
     9 import org.springframework.context.ApplicationContext;
    10 import org.springframework.context.support.ClassPathXmlApplicationContext;
    11 
    12 import cn.smbms.pojo.User;
    13 import cn.smbms.service.user.UserService;
    14 
    15 public class UserTest {
    16 
    17     private Logger logger = Logger.getLogger(UserTest.class);
    18 
    19     @Before
    20     public void setUp() throws Exception {
    21     }
    22 
    23     @Test
    24     public void testGetUserList() {
    25         ApplicationContext ctx = new ClassPathXmlApplicationContext(
    26                 "applicationContext.xml");
    27         UserService userService = (UserService) ctx.getBean("userService");
    28         List<User> userList = new ArrayList<User>();
    29         User userCondition = new User();
    30         userCondition.setUserName("赵");
    31         userCondition.setUserRole(3);
    32         userList = userService.findUsersWithConditions(userCondition);
    33 
    34         for (User userResult : userList) {
    35 //            logger.debug("testGetUserList userCode: "
    36 //                    + userResult.getUserCode() + " and userName: "
    37 //                    + userResult.getUserName() + " and userRole: "
    38 //                    + userResult.getUserRole() + " and userRoleName: "
    39 //                    + userResult.getUserRoleName() + " and address: "
    40 //                    + userResult.getAddress());
    41             System.out.println(userResult.getUserName());
    42         }
    43     }
    44 
    45 }
    View Code

    B、第一种方式:配置SqlSessionFactoryBean+采用数据映射器(MapperFactoryBean)

    a、项目结构(dao层少了impl)

    b、applicationContext.xml(主要变化在xml文件里)

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
     4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
     5     xsi:schemaLocation="http://www.springframework.org/schema/beans
     6     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
     7     http://www.springframework.org/schema/aop
     8     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
     9     http://www.springframework.org/schema/tx
    10     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    11 
    12     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    13         destroy-method="close">
    14         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    15 
    16         <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
    17                         useUnicode=true&amp;characterEncoding=utf-8" />
    18         <property name="username" value="root" />
    19         <property name="password" value="root" />
    20     </bean>
    21 
    22     <!-- 配置SqlSessionFactoryBean -->
    23     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    24         <!-- 引用数据源组件 -->
    25         <property name="dataSource" ref="dataSource" />
    26         <!-- 引用MyBatis配置文件中的配置 -->
    27         <property name="configLocation" value="classpath:mybatis-config.xml" />
    28         <!-- 配置SQL映射文件信息 -->
    29         <!-- <property name="mapperLocations">
    30             <list>
    31                 <value>classpath:cn/smbms/dao/**/*.xml</value>
    32             </list>
    33         </property> -->
    34     </bean>
    35     <!-- 配置DAO --><!-- 采用数据映射器(MapperFactoryBean)的方式完成对数据库操作-->
    36     <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    37     <!-- 根据Mapper接口获取Mapper对象,它封装了原有的SqlSession.getMapper()功能的实现-->
    38         <property name="mapperInterface" value="cn.smbms.dao.user.UserMapper" /><!-- 指定映射器,只能是接口类型 -->
    39         <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    40     </bean>                                    <!-- 注入SqlSessionFactory以提供SqlSessionTemplate实例 -->    
    41     
    42     <!-- 配置业务Bean -->
    43     <bean id="userService" class="cn.smbms.service.user.UserServiceImpl">
    44         <property name="userMapper" ref="userMapper" />
    45     </bean>
    46 </beans>
    View Code

    c、UserServiceImpl.java(发生变化)

     1 package cn.smbms.service.user;
     2 
     3 import java.util.List;
     4 import cn.smbms.dao.user.UserMapper;
     5 import cn.smbms.pojo.User;
     6 
     7 public class UserServiceImpl implements UserService {
     8     private UserMapper userMapper;
     9 
    10     @Override
    11     public List<User> findUsersWithConditions(User user) {
    12         try {
    13             return userMapper.getUserList(user);
    14         } catch (RuntimeException e) {
    15             e.printStackTrace();
    16             throw e;
    17         }
    18     }
    19 
    20     public UserMapper getUserMapper() {
    21         return userMapper;
    22     }
    23 
    24     public void setUserMapper(UserMapper userMapper) {
    25         this.userMapper = userMapper;
    26     }
    27 
    28 }
    View Code

    C、第三种方式:配置SqlSessionFactoryBean+MapperScannerConfigurer(递归扫描基准包下所有接口,若它们在SQL映射文件中 定义过,则动态注册为MapperFactoryBean,如此即可批量产生映射器实现类)+注解

    a、applicationContext.xml(主要变化在xml文件里)

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xmlns:p="http://www.springframework.org/schema/p"
     5     xmlns:aop="http://www.springframework.org/schema/aop"
     6     xmlns:tx="http://www.springframework.org/schema/tx"
     7     xmlns:context="http://www.springframework.org/schema/context"
     8     xsi:schemaLocation="http://www.springframework.org/schema/beans
     9     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    10     http://www.springframework.org/schema/aop
    11     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    12     http://www.springframework.org/schema/tx
    13     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    14     http://www.springframework.org/schema/context
    15     http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    16 
    17     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    18         destroy-method="close">
    19         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    20         <!-- <property name="url">
    21             <value><![CDATA[jdbc:mysql://127.0.0.1:3306/smbms?
    22                     useUnicode=true&characterEncoding=utf-8]]></value>
    23         </property> -->
    24         <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
    25                         useUnicode=true&amp;characterEncoding=utf-8" />
    26         <property name="username" value="root" />
    27         <property name="password" value="root" />
    28     </bean>
    29 
    30     <!-- 配置SqlSessionFactoryBean -->
    31     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    32         <!-- 引用数据源组件 -->
    33         <property name="dataSource" ref="dataSource" />
    34         <!-- 引用MyBatis配置文件中的配置 -->
    35         <property name="configLocation" value="classpath:mybatis-config.xml" />
    36     </bean>
    37     
    38     <!-- MapperScannerConfigurer递归扫描基准包下所有接口,若它们在SQL映射文件中   定义过,
    39                 则动态注册为MapperFactoryBean,如此即可批量产生映射器实现类-->    
    40     <!-- 配置DAO -->
    41     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    42         <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->
    43         <property name="basePackage" value="cn.smbms.dao" /><!-- 指定扫描的基准包  -->
    44     </bean>
    45     <!-- 配置业务Bean -->
    46     <!-- <bean id="userService" class="cn.smbms.service.user.UserServiceImpl">
    47         <property name="userMapper" ref="userMapper" />
    48     </bean> -->
    49     <context:component-scan base-package="cn.smbms.service" />
    50 </beans>
    View Code

    b、UserServiceImpl.java(发生变化)

     1 package cn.smbms.service.user;
     2 
     3 import java.util.List;
     4 
     5 import javax.annotation.Resource;
     6 
     7 import org.springframework.beans.factory.annotation.Autowired;
     8 import org.springframework.stereotype.Service;
     9 
    10 import cn.smbms.dao.user.UserMapper;
    11 import cn.smbms.pojo.User;
    12 
    13 @Service("userService")
    14 public class UserServiceImpl implements UserService {
    15     @Autowired // @Resource
    16     private UserMapper userMapper;
    17 
    18     @Override
    19     public List<User> findUsersWithConditions(User user) {
    20         try {
    21             return userMapper.getUserList(user);
    22         } catch (RuntimeException e) {
    23             e.printStackTrace();
    24             throw e;
    25         }
    26     }
    27     
    28 //    public UserMapper getUserMapper() {
    29 //        return userMapper;
    30 //    }
    31 //
    32 //    public void setUserMapper(UserMapper userMapper) {
    33 //        this.userMapper = userMapper;
    34 //    }
    35 
    36 }
    View Code

    D、业务层添加声明式事务

    a.applicationContext.xml文件中声明

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xmlns:p="http://www.springframework.org/schema/p"
     5     xmlns:context="http://www.springframework.org/schema/context"
     6     xmlns:aop="http://www.springframework.org/schema/aop"
     7     xmlns:tx="http://www.springframework.org/schema/tx"
     8     xsi:schemaLocation="http://www.springframework.org/schema/beans
     9     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    10     http://www.springframework.org/schema/context
    11     http://www.springframework.org/schema/context/spring-context-3.2.xsd
    12     http://www.springframework.org/schema/tx
    13     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    14     http://www.springframework.org/schema/aop
    15     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
    16 
    17     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    18         destroy-method="close">
    19         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    20         <!-- <property name="url">
    21             <value><![CDATA[jdbc:mysql://127.0.0.1:3306/smbms?
    22                     useUnicode=true&characterEncoding=utf-8]]></value>
    23         </property> -->
    24         <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
    25                         useUnicode=true&amp;characterEncoding=utf-8" />
    26         <property name="username" value="root" />
    27         <property name="password" value="root" />
    28     </bean>
    29 
    30     <!-- 配置SqlSessionFactoryBean -->
    31     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    32         <!-- 引用数据源组件 -->
    33         <property name="dataSource" ref="dataSource" />
    34         <!-- 引用MyBatis配置文件中的配置 -->
    35         <property name="configLocation" value="classpath:mybatis-config.xml" />
    36     </bean>
    37     <!-- 配置DAO -->
    38     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    39         <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->
    40         <property name="basePackage" value="cn.smbms.dao" />
    41     </bean>
    42     <!-- 配置业务Bean -->
    43     <!-- <bean id="userService" class="cn.smbms.service.user.UserServiceImpl">
    44         <property name="userMapper" ref="userMapper" />
    45     </bean> -->
    46     <context:component-scan base-package="cn.smbms.service" />
    47     
    48     <!-- 定义事务管理器 -->
    49     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    50         <property name="dataSource" ref="dataSource"></property>
    51     </bean>
    52     <tx:advice id="txAdvice">
    53         <tx:attributes>
    54             <tx:method name="find*" propagation="SUPPORTS"  read-only="true"/>
    55             <tx:method name="get*" propagation="SUPPORTS"  read-only="true"/>
    56             <tx:method name="search*" propagation="SUPPORTS"  read-only="true"/>
    57             <tx:method name="add*" propagation="REQUIRED" />
    58             <tx:method name="save*" propagation="REQUIRED" />
    59             <tx:method name="del*" propagation="REQUIRED" />
    60             <tx:method name="remove*" propagation="REQUIRED" />
    61             <tx:method name="update*" propagation="REQUIRED" />
    62             <tx:method name="modify*" propagation="REQUIRED" />
    63             <tx:method name="*" propagation="REQUIRED" />
    64         </tx:attributes>
    65     </tx:advice>
    66 
    67     <!-- 定义切面 -->
    68     <aop:config>
    69         <aop:pointcut id="serviceMethod"
    70             expression="execution(* cn.smbms.service..*.*(..))" />
    71         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
    72     </aop:config>
    73 </beans>
    View Code

    E、注解实现声明式事务处理

    a、UserServiceImpl.java

     1 package cn.smbms.service.user;
     2 
     3 import java.util.List;
     4 
     5 import javax.annotation.Resource;
     6 
     7 import org.springframework.beans.factory.annotation.Autowired;
     8 import org.springframework.stereotype.Service;
     9 import org.springframework.transaction.annotation.Propagation;
    10 import org.springframework.transaction.annotation.Transactional;
    11 
    12 import cn.smbms.dao.user.UserMapper;
    13 import cn.smbms.pojo.User;
    14 
    15 @Transactional
    16 @Service("userService")
    17 public class UserServiceImpl implements UserService {
    18     @Autowired // @Resource
    19     private UserMapper userMapper;
    20 
    21     @Override
    22     @Transactional(propagation = Propagation.SUPPORTS)
    23     public List<User> findUsersWithConditions(User user) {
    24         try {
    25             return userMapper.getUserList(user);
    26         } catch (RuntimeException e) {
    27             e.printStackTrace();
    28             throw e;
    29         }
    30     }
    31 
    32     @Override
    33     @Transactional(propagation=Propagation.REQUIRED)
    34     public boolean addNewUser(User user) {
    35         boolean result = false;
    36         try {
    37             if (userMapper.add(user) == 1)
    38                 result = true;
    39             // int i = 1 / 0;
    40         } catch (RuntimeException e) {//抛出运行时异常会事务回滚
    41             e.printStackTrace();
    42             throw e;
    43         }
    44         return result;
    45     }
    46     
    47 //    public UserMapper getUserMapper() {
    48 //        return userMapper;
    49 //    }
    50 //
    51 //    public void setUserMapper(UserMapper userMapper) {
    52 //        this.userMapper = userMapper;
    53 //    }
    54 
    55 }
    View Code

    b、applicationContext.xml(添加对注解配置的事务的支持)

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xmlns:p="http://www.springframework.org/schema/p"
     5     xmlns:context="http://www.springframework.org/schema/context"
     6     xmlns:aop="http://www.springframework.org/schema/aop"
     7     xmlns:tx="http://www.springframework.org/schema/tx"
     8     xsi:schemaLocation="http://www.springframework.org/schema/beans
     9     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    10     http://www.springframework.org/schema/context
    11     http://www.springframework.org/schema/context/spring-context-3.2.xsd
    12     http://www.springframework.org/schema/tx
    13     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    14     http://www.springframework.org/schema/aop
    15     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
    16 
    17     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    18         destroy-method="close">
    19         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    20         <!-- <property name="url">
    21             <value><![CDATA[jdbc:mysql://127.0.0.1:3306/smbms?
    22                     useUnicode=true&characterEncoding=utf-8]]></value>
    23         </property> -->
    24         <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
    25                         useUnicode=true&amp;characterEncoding=utf-8" />
    26         <property name="username" value="root" />
    27         <property name="password" value="root" />
    28     </bean>
    29 
    30     <!-- 配置SqlSessionFactoryBean -->
    31     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    32         <!-- 引用数据源组件 -->
    33         <property name="dataSource" ref="dataSource" />
    34         <!-- 引用MyBatis配置文件中的配置 -->
    35         <property name="configLocation" value="classpath:mybatis-config.xml" />
    36     </bean>
    37     <!-- 配置DAO -->
    38     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    39         <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->
    40         <property name="basePackage" value="cn.smbms.dao" />
    41     </bean>
    42     <!-- 配置业务Bean -->
    43     <!-- <bean id="userService" class="cn.smbms.service.user.UserServiceImpl">
    44         <property name="userMapper" ref="userMapper" />
    45     </bean> -->
    46     <context:component-scan base-package="cn.smbms.service" />
    47     <!-- 定义事务管理器 -->
    48     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    49         <property name="dataSource" ref="dataSource"></property>
    50     </bean>
    51     <tx:annotation-driven transaction-manager="transactionManager"/><!-- 添加对注解配置的事务的支持 -->
    52     <!-- <tx:advice id="txAdvice">
    53         <tx:attributes>
    54             <tx:method name="find*" propagation="SUPPORTS" />
    55             <tx:method name="add*" propagation="REQUIRED" />
    56             <tx:method name="del*" propagation="REQUIRED" />
    57             <tx:method name="update*" propagation="REQUIRED" />
    58             <tx:method name="*" propagation="REQUIRED" />
    59         </tx:attributes>
    60     </tx:advice> -->
    61     <!-- 定义切面 -->
    62     <!-- <aop:config>
    63         <aop:pointcut id="serviceMethod"
    64             expression="execution(* cn.smbms.service..*.*(..))" />
    65         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
    66     </aop:config> -->
    67 </beans>
    View Code

    常用两个事务:

    REQUIRED(默认值增删改):在有transaction状态下执行;如当前没有transaction,则创建新的transaction;
    SUPPORTS(查询):如当前有transaction,则在transaction状态下执行;如果当前没有transaction,在无transaction状态下执行;

    注意:

    Spring默认只在抛出runtime exception时才标识事务回滚

    欢迎进群学习交流(927465926) Full Stack engineer

  • 相关阅读:
    工作的思考十七:工作中容易犯的错误
    学习之路三十四:再一次重构缓存设计
    学习之路三十五:Android和WCF通信
    学习之路二十:两周工作技术总结
    学习之路三十三:重构技巧的学习
    工作的思考十五:升职前需要做的准备(TeamLeader)
    学习之路三十二:VS调试的简单技巧
    maven pom
    maven环境配置
    maven的背景
  • 原文地址:https://www.cnblogs.com/wtzl/p/8798318.html
Copyright © 2020-2023  润新知