MyBatis搭配spring和事务配置

来源:互联网 发布:清华经管知乎 编辑:程序博客网 时间:2024/05/17 04:36

我这里做的例子是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
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 光大乐惠金卡信用卡还了怎么办 增驾期间被扣3分怎么办 a2驾驶证被扣12分后怎么办 我手机换号码了驾驶证档案怎么办 手机号码换了查不到驾照分了怎么办 金牛区源泉幼儿园摇不到号怎么办 b2驾驶证被扣12分后怎么办 福建省超过一年驾照未年审要怎么办 为缓解交通拥堵现状人们应该怎么办 告对方不知道对方出身日期怎么办 上海业余围棋4进3老不过怎么办 孩子想上学但又怕同学议论怎么办 在菲律宾黑了博彩老板的钱怎么办 九阴真经3d先遣服更新失败怎么办 公司核名通过不想用了怎么办 公司核名下来了不想注册了怎么办 家人受到小贷公司催款威胁怎么办 商标抽签资料提交上去有问题怎么办 花椒直播助手苹果版下载不了怎么办 在香港酒店住把床单弄上血了怎么办 综英美我能怎么办我也很绝望百度云 护照的名字中间有个空格怎么办 开车不小心压死黄鼠狼了怎么办 三户联保贷款一方不还怎么办 因为隔断中介违约…我该怎么办 上海居住证没下来换住址了怎么办 工商注册后大股东不注资怎么办 公司不给去办理变更股东信息怎么办 滴滴车主注册没有自己的车型怎么办 代办用虚假地址注册的公司怎么办? 写字楼注册公司租户不租了怎么办 租户没把公司迁出我该怎么办 租户不肯把户口迁出了业主怎么办 同片区个体户营业场所搬迁怎么办 个体领发票的本丢了怎么办 领房产证发票和合同丢了怎么办 税务登记证5年没有办怎么办 二证合一后税务登记证怎么办? 微信漂流瓶打招呼对方收不到怎么办 添加不上徽信好友的微信帐号怎么办 手机号码不用了微信密码忘了怎么办