Mybatis和Spring整合的几种方式

3 篇文章 0 订阅
1 篇文章 0 订阅

这两天学习mybatis,需要整合到spring中,整理了几种整合方式

Mybatis和Spring的整合

Jar的准备:

Spring的核心,mybatis的核心,数据库驱动,mybatis-spring,以及日志等一些包

第一种整合方式:

不需要mybatis-config.xml配置文件,也不需要mapper.xml配置文件,所有的配置都放在Spring的applicationContext.xml配置文件中配置,使用注解的方式来写SQL语句,使用mapper接口的方式来整合

Spring核心配置:

<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">

        <propertyname="dataSource"ref="dataSource"/>

    </bean>

 

<beanid="userMapper"class="org.mybatis.spring.mapper.MapperFactoryBean">

      <propertyname="mapperInterface"value="com.mrx.mapper.MapperTest"/>

      <propertyname="sqlSessionFactory"ref="sqlSessionFactory"/>

    </bean>

<!--加载jdbc的配置文件 -->

<context:property-placeholderlocation="classpath:jdbc.properties"/>

dataSource可以自定,这里使用的是c3p0来作为连接池,其中的配置信息根据条件自行修改即可

<beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

            <!-- =========== 数据库连接信息 =========== -->

        <propertyname="jdbcUrl"value="${url}"></property>

        <propertyname="driverClass"value="${driver}"></property>

        <propertyname="user"value="${username}"></property>

        <propertyname="password"value="${password}"></property>

        <!-- =========== 连接池的管理配置 =========== -->

        <!--初始化时获取三个连接,取值应在minPoolSizemaxPoolSize之间。Default: 3 -->

        <propertyname="initialPoolSize"value="3"></property>

        <!--连接池中保留的最小连接数。Default: 3 -->

        <propertyname="minPoolSize"value="3"></property>

        <!--连接池中保留的最大连接数。Default: 15 -->

        <propertyname="maxPoolSize"value="5"></property>

        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->

        <propertyname="acquireIncrement"value="3"></property>

        <!-- 控制数据源内加载的PreparedStatements数量。如果maxStatementsmaxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->

        <propertyname="maxStatements"value="8"></property>

        <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->

        <propertyname="maxStatementsPerConnection"value="5"></property>

        <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->

        <propertyname="maxIdleTime"value="1800"></property>

      </bean>

至此,核心配置完成

mapper接口:

public interface MapperTest {

    @Select("SELECT* FROM T_USER")

    public List<User> selectSimpleUser(@Param("id")Integerid);

}

测试类:

public void TestSpringMapper(){

        ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");

        MapperTest mt = (MapperTest)context.getBean("userMapper");

        List<User> list = mt.selectSimpleUser(null);

        for(Useroc :list){

            System.out.println(oc);

        }

    }

至此,第一种整合方式完成,该方式使用注解SQL来代替mapper.xml配置文件,把mybatis-config.xml配置文件完全舍弃。

第二种整合方式:

主要的变化就是用mapper.xml代替了第一种方式里的注解的形式

核心配置:

在第一种配置的基础上添加了SqlSession这个Bean,添加了SqlSessionFactory的属性配置,dataSource的配置和第一个方式完全一样

<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">

        <propertyname="dataSource"ref="dataSource"/>

        <!-- 第一种方式配置mapper.xml文件 -->

        <!-- <propertyname="configLocation" value="classpath:mybatis-config.xml"/> -->

        <!-- 第二种方式配置mapper.xml文件 -->

        <property name="mapperLocations" value="classpath*:com/mrx/mapper/*.xml"/>

    </bean>

 

<beanid="sqlSession"class="org.mybatis.spring.SqlSessionTemplate">

        <constructor-argindex="0"ref="sqlSessionFactory"/>

    </bean>

mybatis-config.xml里面只配置了日志和mapper

<configuration>

  <settings>

    <settingname="logImpl"value="LOG4J"/>

  </settings>

  <mappers>

    <mapperresource="com/mrx/mapper/simpleUser.xml"/>

  </mappers>

</configuration>

测试类:这里因为没有配置mapper接口,所以使用SqlSession自带的方法来获取执行SQL语句

public void TestSqlStatement(){

        ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");

        SqlSessionTemplate ss = (SqlSessionTemplate)context.getBean("sqlSession");

        List<User> list = ss.selectList("com.mrx.mybatis.mapper.mapper.OrdersCustomMapper.selectSimpleUser",null);

        for(Useroc :list){

            System.out.println(oc);

        }

    }

第三种方式:

通过SqlSessionDaoSupport来获取到SqlSession,在Dao中,继承SqlSessionDaoSupport就行

其他的SqlSessionFacrtory,SqlSession和dataSource的配置和上面一样,配置了就行,本质就是提前把SqlSessionFactory注入到SqlSessionDaoSupport中,方便使用

整理下来,核心就是下面几点:

1.SqlSessionFactory交给Spring管理

2.SqlSession交给Spring管理

3.数据库连接信息告诉Spring去创建连接池(这部分其实就是把原来放在mybatis-config.xml里面的配置放到了这里),把连接池给SqlSessionFactory去创建SqlSession

4.如何告诉mybatis,配置好的映射文件(mapper.xml)?

<!--第一种方式配置mapper.xml文件 -->

        <property name="configLocation" value="classpath:mybatis-config.xml"/> 

这是把映射文件用mapper标签写在mybatis-config.xml中

        <!-- 第二种方式配置mapper.xml文件 -->

        <property name="mapperLocations" value="classpath*:com/mrx/mapper/*.xml"/>

这是使用通配符的方式来匹配到mapper.xml

如果想用Mapper接口来使用的话,就这样配置

<beanid="userMapper"class="org.mybatis.spring.mapper.MapperFactoryBean">

      <propertyname="mapperInterface"value="com.mrx.mapper.MapperTest"/>

      <propertyname="sqlSessionFactory"ref="sqlSessionFactory"/>

    </bean>

最后是事务的配置,下面是xml和注解两种形式的配置方式

mybatis-spring事务的配置

<!--事务配置开始 -->

    <!-- 配置事务管理此处的数据源必须和sqlSession的数据源一致-->

    <beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <propertyname="dataSource"ref="dataSource"/>

    </bean>

    <!-- 事务规则控制,比如回滚,传播属性,是否只读等 -->

    <tx:adviceid="TxAdvice"transaction-manager="transactionManager">

        <tx:attributes>

            <tx:methodname="*"/>

        </tx:attributes>

    </tx:advice>

    <!-- 事务切面 -->

    <aop:config>

        <aop:pointcutexpression="execution( * com.mrx.mapper.MapperTest.*(..))"id="pointcuter"/>

        <aop:advisoradvice-ref="TxAdvice"pointcut-ref="pointcuter"/>

    </aop:config>

<!--事务配置结束 -->

注解式配置

<!--事务配置开始 -->

    <!-- 配置事务管理此处的数据源必须和sqlSession的数据源一致-->

    <beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <propertyname="dataSource"ref="dataSource"/>

    </bean>

    <tx:annotation-driventransaction-manager="transactionManager"/>

    <!-- 事务配置结束 -->

整合到这里就结束了,接下来就要看下整合的原理和一些细节方面的东西了。坚持!!!


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值