关闭

MyBatis搭配spring和事务配置

标签: springmybatis
765人阅读 评论(0) 收藏 举报
分类:

我这里做的例子是mybatis。

一:需要的jar
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
二:配置
  • applicationContext.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:dubbo="http://code.alibabatech.com/schema/dubbo"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans        
    http://www.springframework.org/schema/beans/spring-beans.xsd    
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd     
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://code.alibabatech.com/schema/dubbo        
    http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <!-- xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" http://code.alibabatech.com/schema/dubbo 
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd" -->
    <!-- 引入配置文件 -->
    <import resource="classpath:dubbo.xml" />

    <!-- 加入注解支持 -->
    <context:component-scan base-package="com.we" />
    <!--引入jdbc的xml文件 -->
    <import resource="classpath:jdbc.xml" />
    <!-- 事务管理,加入对事务的支持 -->
    <tx:annotation-driven transaction-manager="transactionManager"
        proxy-target-class="true"></tx:annotation-driven>

    <!-- 把datasource委托给DataSourceTransactionManager-->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置Mybatis的 SqlSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis.xml"></property>
    </bean>
    <!-- 配置Myabtis对dao的扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.we.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>
  • jdbc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
    http://www.springframework.org/schema/task   
    http://www.springframework.org/schema/task/spring-task-3.1.xsd   
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">


    <context:property-placeholder location="classpath:jdbc.properties"
        ignore-unresolvable="true" />

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="20" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize"
            value="20" />
        <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
        <property name="filters" value="stat" />
    </bean>
</beans>
  • mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC  
    "-//mybatis.org//DTD Config 3.0//EN"  
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <mapper resource="com/we/dao/PersonDao.xml" />
    </mappers>
</configuration>
3代码
package com.we.dao;

import com.we.entry.Person;

public interface PersonDao {

    public Person get(int id);

    // public List<Person> getAll();
    //
    // public int insert(Person person);
    //
    public int updateById(Person user);
    //
    // public int delete(int id);
}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"   
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.we.dao.PersonDao">
    <select id="get" parameterType="com.we.entry.Person" resultMap="result">
        select * from person WHERE id=#{id}
    </select>

    <resultMap type="com.we.entry.Person" id="result">
        <id column="id" property="id" />
        <result column="name" property="name" />
    </resultMap>

    <update id="updateById" parameterType="com.we.entry.Person">
        update person set
        name=#{name}  where id=#{id}
    </update>
</mapper>
4测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class MyTest {

    @Resource
    private PersonDao userDao;

    @Test
    public void testAddition() {
        assertEquals(userDao.get(1) != null, true);
    }

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        PersonService o = (PersonService) ctx.getBean("ps");
        o.testTx();


    }

}

下面是事务相关的代码

@org.springframework.stereotype.Service("ps")
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonDao personDao;

    // 可以通过加上该注解,和去掉对比测试。
    @Transactional
    public void testTx() {
        Person p = new Person();
        p.setId(1);
        p.setName("3333");
        personDao.updateById(p);
        int i = 1 / 0;// 使代码抛出异常
        p.setId(2);
        personDao.updateById(p);
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:44913次
    • 积分:1474
    • 等级:
    • 排名:千里之外
    • 原创:97篇
    • 转载:4篇
    • 译文:0篇
    • 评论:12条
    文章分类
    最新评论