设为首页 收藏本站
查看: 1154|回复: 0

[经验分享] spring与mybatis四种整合方法

[复制链接]

尚未签到

发表于 2016-11-26 06:08:38 | 显示全部楼层 |阅读模式
  
1、采用数据映射器(MapperFactoryBean)的方式,不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数。
  (1)Spring配置文件:
  <!-- 引入jdbc配置文件 -->
     <context:property-placeholder location="jdbc.properties"/>
  <!--创建jdbc数据源 -->
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
        <property name="initialSize" value="${initialSize}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="maxIdle" value="${maxIdle}"/>
        <property name="minIdle" value="${minIdle}"/>
      </bean>
  <!-- 创建SqlSessionFactory,同时指定数据源-->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      </bean>
  <!--创建数据映射器,数据映射器必须为接口-->
      <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
      <property name="mapperInterface" value="com.xxt.ibatis.dbcp.dao.UserMapper" />
      <property name="sqlSessionFactory" ref="sqlSessionFactory" />
      </bean>
  <bean id="userDaoImpl2" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl2">
      <property name="userMapper" ref="userMapper"/>
 </bean>
 
(2)数据映射器UserMapper,代码如下:
  public interface UserMapper {
        @Select("SELECT * FROM user WHERE id = #{userId}")
        User getUser(@Param("userId") long id);
  }
 (3) dao接口类UserDao,代码如下:
   public interface UserDao {
       public User getUserById(User user);
   }
(4)dao实现类UserDaoImpl2,,代码如下:
  public class UserDaoImpl2 implements UserDao {
       private UserMapper userMapper;
  public void setUserMapper(UserMapper userMapper) {
           this.userMapper = userMapper;
       } 
  public User getUserById(User user) {
          return userMapper.getUser(user.getId());
       }
   }

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

    (2)mybatis总配置文件sqlMapConfig.xml:
  <configuration>
   <typeAliases>
     <typeAlias type="com.xxt.ibatis.dbcp.domain.User" alias="User" />
  </typeAliases>
   <mappers>
      <mapper resource="com/xxt/ibatis/dbcp/domain/user.map.xml" />
     </mappers>
 </configuration>
(3)实体类映射文件user.map.xml:
<mapper namespace="com.xxt.ibatis.dbcp.domain.User">
     <resultMap type="User" id="userMap">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="password" column="password" />
        <result property="createTime" column="createtime" />
     </resultMap>
     <select id="getUser" parameterType="User" resultMap="userMap">
       select * from user where id = #{id}
     </select>
<mapper/>
(4)dao层接口实现类UserDaoImpl:
  public class UserDaoImpl implements  UserDao  {
     public SqlSessionTemplate sqlSession;
     public User getUserById(User user) {
         return (User)sqlSession.selectOne("com.xxt.ibatis.dbcp.domain.User.getUser", user);
     }
     public void setSqlSession(SqlSessionTemplate sqlSession) {
          this.sqlSession = sqlSession;
     }
   }
3、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession。
   (1)spring配置文件:
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
   <property name="dataSource" ref="dataSource" />
   <property  name="configLocation"  value="classpath:sqlMapConfig.xml"/>
   <!-- <property  name="mapperLocations"  value="classpath*:com/xxt/ibatis/dbcp/domain/user.map.xml"/   >  -->
</bean>
  <bean id="sqlSession"     class="org.mybatis.spring.SqlSessionTemplate">
      <constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
  <bean id="userDaoImpl3" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl3">
   <!--注入SqlSessionTemplate实例 -->
   <property name="sqlSessionTemplate" ref="sqlSession" />
   <!--也可直接注入SqlSessionFactory实例,二者都指定时,SqlSessionFactory失效 -->
   <!-- <property name="sqlSessionFactory" ref="sqlSessionFactory" />
-->
</bean>
 (2) dao层接口实现类UserDaoImpl3:
public class UserDaoImpl3 extends SqlSessionDaoSupport implements UserDao {  
  public User getUserById(User user) {  
     return (User) getSqlSession().selectOne("com.xxt.ibatis.dbcp.domain.User.getUser", user);  
  }  
}
3、采用org.mybatis.spring.mapper.MapperFactoryBean或者org.mybatis.spring.mapper.MapperScannerConfigurer
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <beans:property name="dataSource" ref="simpleDataSource" />
        <beans:property name="configLocation"
            value="classpath:conf/core/mybatis-config.xml" />
    </beans:bean>

    <beans:bean id="sqlSessionFactory_contact" class="org.mybatis.spring.SqlSessionFactoryBean">
        <beans:property name="dataSource" ref="simpleDataSource_contact" />
        <beans:property name="configLocation"
            value="classpath:conf/core/mybatis-config-contact.xml" />
    </beans:bean>

    <beans:bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <beans:property name="dataSource" ref="simpleDataSource" />
    </beans:bean>

    <beans:bean id="transactionManager_contact"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <beans:property name="dataSource" ref="simpleDataSource_contact" />
    </beans:bean>
   

    <!--  <tx:annotation-driven transaction-manager="transactionManager" />
    <tx:annotation-driven transaction-manager="transactionManager_contact" />
    -->   
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.mybatis.UserDao"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <bean id="userService" class="com.mybatis.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>

    <!-- 加载配置文件 -->
    <beans:bean name="mapperScannerConfigurer"
        class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <beans:property name="basePackage" value="com.elong.hotel.crm.data.mapper" />
        <beans:property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></beans:property>
    </beans:bean>
    <beans:bean name="mapperScannerConfigurer_contact"
        class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <beans:property name="basePackage"
            value="com.elong.hotel.crm.data.contact.mapper" />
        <beans:property name="sqlSessionFactoryBeanName" value="sqlSessionFactory_contact"></beans:property>
    </beans:bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- name表示以什么开始的方法名,比如 add*表示add开头的方法 propagation表示事务传播属性,不写默认有 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="del*" />
            <tx:method name="update*" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="search*" read-only="true" />
        </tx:attributes>
    </tx:advice>
   
    <tx:advice id="txAdvice_contact" transaction-manager="transactionManager_contact">
        <tx:attributes>
            <!-- name表示以什么开始的方法名,比如 add*表示add开头的方法 propagation表示事务传播属性,不写默认有 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="del*" />
            <tx:method name="update*" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="search*" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切面 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.elong.hotel.crm.service..*.*(..))"
            id="pointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
        <aop:advisor advice-ref="txAdvice_contact" pointcut-ref="pointcut" />
    </aop:config>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-305546-1-1.html 上篇帖子: MyBatis 实现简单的 增加 查找 下篇帖子: maven搭建springmvc+spring+mybatis实例
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表