zoukankan      html  css  js  c++  java
  • MyBatis与Spring整合

    1.单独使用MyBatis

    单独使用MyBatis,不结合其他框架,主要步骤是:

    1.创建SqlSessionFactory对象

    创建方法是通过SqlSessionFactoryBuilder这个类从mybatis的XML配置文件,或者porperties,或者URL获取相关数据库的配置信息。

    2.从sqlSessionFactory获取SqlSession。

    3.使用SqlSession提供的API,对数据库进行增删改查,以及事务管理。

    1
    2
    3
    4
    5
    6
    7
    String resource = "org/mybatis/example/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession session = sqlSessionFactory.openSession();
    session.insert("BlogMapper.selectBlog", 101);
    session.commit();
    sesssion.close();

    2.结合Spring框架使用MyBatis

     MyBatis + Spring的使用方式,一般是在Spring的配置文件里,配置以下内容:

    1.数据源(DataSource)

    2.SqlSessionFactoryBean,实现FactoryBean接口,通过注入DataSource对象,以及MyBatis的相关配置信息,返回SQLSessionFactory对象。

    1
    2
    3
    4
    5
    6
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/mysql"></jee:jndi-lookup>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property>
    </bean>

    加入以上的配置信息就可以Dao类里,直接引用sqlSessionFactory这个对象,对数据库进行操作(跟1的代码一样)。

    如果Dao的代码写多了,这时候会发现,每次的数据库操作,步骤都是要先

    ①获取SqlSession对象->②调用数据库操作的方法->③提交事务->④关闭SqlSession

    其中①③④这三个步骤会一直环绕在每个Dao的方法里。

    这时候会这么想,能否提供这样一个功能,在调用方法之前自动获取SqlSession对象,在调用方法之后自动提交事务和关闭SqlSession对象。这样①③④这样重复的代码就可以剔除了,整个Dao类的代码也变得更加简洁。

    3.SqlSessionTemplate的应用

    上面提到的,在调用方法之前和调用方法之后,各执行一些操作。这种技术一下子就联想到就是AOP编程方式。

    AOP是Spring的第二个核心功能,所以自然它也提供了这样的是一个实现类,就是SqlSessionTemplate

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/mysql"></jee:jndi-lookup>
     
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property>
    </bean>
         
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory" />
    </bean>

     引入SqlSessionTemplate这个类,在写Dao时,每个方法,在执行之前,自动获取SqlSession对象,执行之后,自动提交事务和关闭会话。

    1
    2
    3
    public Object save(String str, Object obj) throws Exception {
      return sqlSessionTemplate.insert(str, obj);
    }

    现在代码一下子变得更简洁了,只剩下数据操作的方法。

    4.SqlSessionTemplate原理解析思路

    为什么SqlSessionTemplate能够在每个方法,在执行之前,自动获取SqlSession对象,执行之后,自动提交事务和关闭会话。

    要知道这个原理,其实相当于要了解Spring AOP原理。

    要了解Spring AOP原理,就必须知道Java技术里,动态代理的原理。

    Java的动态代理主要是涉及到JDK里java.lang.reflect包下的InvocationHandler接口和Proxy类里创建代理对象的方法。

    SqlSessionTemplate的源码解析

    SqlSessionTemplate的构造方法里,创建了一个SqlSession的代理对象。

    在这个代理对象,每次SQLSession的方法被调用,都执行以下操作。

    上面代码涉及到的知识点比较多,要完全理解,需要掌握下面列出的几点。

    5.知识点归纳

    1.MyBatis中的SqlSessionFactory和SqlSession

    2.Spring中的SqlSessionFactoryBean和SqlSessionTemplate

    3.Spring AOP原理

    4.Java动态代理原理

    5.Java反射原理

    Spring与Mybatis四种整合方法

     
     


    1、采用数据映射器(MapperFactoryBean)的方式,不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数。
      (1)Spring配置文件:

         

    1. <!-- 引入jdbc配置文件 -->  
    2.      <context:property-placeholder location="jdbc.properties"/>  
    3.       <!--创建jdbc数据源 -->  
    4.       <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
    5.         <property name="driverClassName" value="${driver}"/>  
    6.         <property name="url" value="${url}"/>  
    7.         <property name="username" value="${username}"/>  
    8.         <property name="password" value="${password}"/>  
    9.         <property name="initialSize" value="${initialSize}"/>  
    10.         <property name="maxActive" value="${maxActive}"/>  
    11.         <property name="maxIdle" value="${maxIdle}"/>  
    12.         <property name="minIdle" value="${minIdle}"/>  
    13.       </bean>  
    14.       <!-- 创建SqlSessionFactory,同时指定数据源-->  
    15.       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
    16.       <property name="dataSource" ref="dataSource" />   
    17.       </bean>  
    18.       <!--创建数据映射器,数据映射器必须为接口-->  
    19.       <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">   
    20.       <property name="mapperInterface" value="com.xxt.ibatis.dbcp.dao.UserMapper" />  
    21.       <property name="sqlSessionFactory" ref="sqlSessionFactory" />   
    22.       </bean>  
    23.       <bean id="userDaoImpl2" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl2">  
    24.       <property name="userMapper" ref="userMapper"/>  
    25.  </bean>  
     
    (2)数据映射器UserMapper,代码如下:
    1. public interface UserMapper {  
    2.       @Select("SELECT * FROM user WHERE id = #{userId}")   
    3.       User getUser(@Param("userId") long id);   
    4. }  


     (3) dao接口类UserDao,代码如下:
    1. public interface UserDao {  
    2.     public User getUserById(User user);  
    3. }  


    (4)dao实现类UserDaoImpl2,,代码如下:

      

    1. public class UserDaoImpl2 implements UserDao {  
    2.        private UserMapper userMapper;  
    3.        public void setUserMapper(UserMapper userMapper) {   
    4.            this.userMapper = userMapper;   
    5.        }   
    6.        public User getUserById(User user) {  
    7.           return userMapper.getUser(user.getId());   
    8.        }  
    9.    }  

     
     2、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate
        mybatis中, sessionFactory可由SqlSessionFactoryBuilder.来创建。MyBatis- Spring 中,使用了SqlSessionFactoryBean来替代。SqlSessionFactoryBean有一个必须属性 dataSource,另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
       (1)Spring配置文件:
      
    1.   <!-- 创建SqlSessionFactory,同时指定数据源-->  
    2.    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
    3.       <property name="dataSource" ref="dataSource" />   
    4.       <!-- 指定sqlMapConfig总配置文件,订制的environment在spring容器中不在生效-->  
    5.       <property  name="configLocation"  value="classpath:sqlMapConfig.xml"/>  
    6.       <!--指定实体类映射文件,可以指定同时指定某一包以及子包下面的所有配置文件,mapperLocations和configLocation 有一个即可,当需要为实体类指定别名时,可指定configLocation属性,再在mybatis总配置文件中采用mapper引入实体类映射文件 -->  
    7.       <!- - <property  name="mapperLocations"  value="classpath*:com/xxt/ibatis/dbcp/**/*.xml"/>  -->  
    8.    </bean>  
    9. <bean id="sqlSession"     class="org.mybatis.spring.SqlSessionTemplate">   
    10.       <constructor-arg index="0" ref="sqlSessionFactory" />   
    11. </bean>  
    12. <bean id="UserDaoImpl " class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl">  
    13.    <!--注入SqlSessionTemplate实例 -->  
    14.    <property name="sqlSessionTemplate" ref="sqlSession" />  
    15. -->  
    16. </bean>  

        (2)mybatis总配置文件sqlMapConfig.xml:
     
    1. <configuration>  
    2.   <typeAliases>  
    3.     <typeAlias type="com.xxt.ibatis.dbcp.domain.User" alias="User" />  
    4.  </typeAliases>  
    5.   <mappers>  
    6.      <mapper resource="com/xxt/ibatis/dbcp/domain/user.map.xml" />  
    7.     </mappers>  
    8. </configuration>  

    (3)实体类映射文件user.map.xml:
    1. <mapper namespace="com.xxt.ibatis.dbcp.domain.User">  
    2.      <resultMap type="User" id="userMap">  
    3.         <id property="id" column="id" />  
    4.         <result property="name" column="name" />  
    5.         <result property="password" column="password" />  
    6.         <result property="createTime" column="createtime" />  
    7.      </resultMap>  
    8.      <select id="getUser" parameterType="User" resultMap="userMap">  
    9.        select * from user where id = #{id}  
    10.      </select>  
    11. <mapper/>  


    (4)dao层接口实现类UserDaoImpl:
    1. public class UserDaoImpl implements  UserDao  {  
    2.    public SqlSessionTemplate sqlSession;  
    3.    public User getUserById(User user) {  
    4.        return (User)sqlSession.selectOne("com.xxt.ibatis.dbcp.domain.User.getUser", user);  
    5.    }  
    6.    public void setSqlSession(SqlSessionTemplate sqlSession) {  
    7.         this.sqlSession = sqlSession;  
    8.    }  
    9.  }  


     3、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession。
       (1)spring配置文件:

     

    1. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
    2.    <property name="dataSource" ref="dataSource" />  
    3.    <property  name="configLocation"  value="classpath:sqlMapConfig.xml"/>  
    4.    <!-- <property  name="mapperLocations"  value="classpath*:com/xxt/ibatis/dbcp/domain/user.map.xml"/   >  -->  
    5. </bean>  
    6.  <bean id="sqlSession"     class="org.mybatis.spring.SqlSessionTemplate">   
    7.       <constructor-arg index="0" ref="sqlSessionFactory" />   
    8. </bean>  
    9. <bean id="userDaoImpl3" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl3">  
    10.    <!--注入SqlSessionTemplate实例 -->  
    11.    <property name="sqlSessionTemplate" ref="sqlSession" />   
    12.    <!--也可直接注入SqlSessionFactory实例,二者都指定时,SqlSessionFactory失效 -->  
    13.    <!-- <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
    14. -->  
    15. </bean>  


     (2) dao层接口实现类UserDaoImpl3:
    1. public class UserDaoImpl3 extends SqlSessionDaoSupport implements UserDao {     
    2.   public User getUserById(User user) {     
    3.      return (User) getSqlSession().selectOne("com.xxt.ibatis.dbcp.domain.User.getUser", user);    
    4.   }     
    5. }  


     4、采用org.mybatis.spring.mapper.MapperFactoryBean或者org.mybatis.spring.mapper.MapperScannerConfigurer
      1. <beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
      2.         <beans:property name="dataSource" ref="simpleDataSource" />  
      3.         <beans:property name="configLocation"  
      4.             value="classpath:conf/core/mybatis-config.xml" />  
      5.     </beans:bean>  
      6.   
      7.     <beans:bean id="sqlSessionFactory_contact" class="org.mybatis.spring.SqlSessionFactoryBean">  
      8.         <beans:property name="dataSource" ref="simpleDataSource_contact" />  
      9.         <beans:property name="configLocation"  
      10.             value="classpath:conf/core/mybatis-config-contact.xml" />  
      11.     </beans:bean>  
      12.   
      13.     <beans:bean id="transactionManager"  
      14.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
      15.         <beans:property name="dataSource" ref="simpleDataSource" />  
      16.     </beans:bean>  
      17.   
      18.     <beans:bean id="transactionManager_contact"  
      19.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
      20.         <beans:property name="dataSource" ref="simpleDataSource_contact" />  
      21.     </beans:bean>  
      22.       
      23.   
      24.     <!--  <tx:annotation-driven transaction-manager="transactionManager" />   
      25.     <tx:annotation-driven transaction-manager="transactionManager_contact" />  
      26.     -->     
      27. <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
      28.         <property name="mapperInterface" value="com.mybatis.UserDao"></property>  
      29.         <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
      30.     </bean>  
      31.   
      32.     <bean id="userService" class="com.mybatis.UserServiceImpl">  
      33.         <property name="userDao" ref="userDao"></property>  
      34.     </bean>  
      35.   
      36.     <!-- 加载配置文件 -->  
      37.     <beans:bean name="mapperScannerConfigurer"  
      38.         class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
      39.         <beans:property name="basePackage" value="com.elong.hotel.crm.data.mapper" />  
      40.         <beans:property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></beans:property>  
      41.     </beans:bean>  
      42.     <beans:bean name="mapperScannerConfigurer_contact"  
      43.         class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
      44.         <beans:property name="basePackage"  
      45.             value="com.elong.hotel.crm.data.contact.mapper" />  
      46.         <beans:property name="sqlSessionFactoryBeanName" value="sqlSessionFactory_contact"></beans:property>  
      47.     </beans:bean>  
      48.   
      49.     <tx:advice id="txAdvice" transaction-manager="transactionManager">  
      50.         <tx:attributes>  
      51.             <!-- name表示以什么开始的方法名,比如 add*表示add开头的方法 propagation表示事务传播属性,不写默认有 -->  
      52.             <tx:method name="save*" propagation="REQUIRED" />  
      53.             <tx:method name="insert*" propagation="REQUIRED" />  
      54.             <tx:method name="add*" propagation="REQUIRED" />  
      55.             <tx:method name="del*" />  
      56.             <tx:method name="update*" />  
      57.             <tx:method name="find*" read-only="true" />  
      58.             <tx:method name="get*" read-only="true" />  
      59.             <tx:method name="search*" read-only="true" />  
      60.         </tx:attributes>  
      61.     </tx:advice>  
      62.       
      63.     <tx:advice id="txAdvice_contact" transaction-manager="transactionManager_contact">  
      64.         <tx:attributes>  
      65.             <!-- name表示以什么开始的方法名,比如 add*表示add开头的方法 propagation表示事务传播属性,不写默认有 -->  
      66.             <tx:method name="save*" propagation="REQUIRED" />  
      67.             <tx:method name="insert*" propagation="REQUIRED" />  
      68.             <tx:method name="add*" propagation="REQUIRED" />  
      69.             <tx:method name="del*" />  
      70.             <tx:method name="update*" />  
      71.             <tx:method name="find*" read-only="true" />  
      72.             <tx:method name="get*" read-only="true" />  
      73.             <tx:method name="search*" read-only="true" />  
      74.         </tx:attributes>  
      75.     </tx:advice>  
      76.     <!-- 配置事务切面 -->  
      77.     <aop:config>  
      78.         <aop:pointcut expression="execution(* com.elong.hotel.crm.service..*.*(..))"  
      79.             id="pointcut" />  
      80.         <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />  
      81.         <aop:advisor advice-ref="txAdvice_contact" pointcut-ref="pointcut" />  
      82.     </aop:config
  • 相关阅读:
    洛谷
    洛谷
    洛谷
    模板
    洛谷
    洛谷
    Codeforces Round #561 (Div. 2) E. The LCMs Must be Large(数学)
    Codeforces Round #561 (Div. 2)
    Mail.Ru Cup 2018 Round 2 C. Lucky Days(拓展欧几里得)
    The 10th Shandong Provincial Collegiate Programming Contest H.Tokens on the Segments(贪心+优先级队列 or 贪心+暴力)
  • 原文地址:https://www.cnblogs.com/fqwsndc1314-5207788/p/7705397.html
Copyright © 2011-2022 走看看