spring之事务管理

1.spring简介
spring中认为一切java类都是资源,而资源都是Bean,容纳这些Bean的是spring提供的Ioc容器,所以Spring是一种基于bean的编程。spring的作用主要是整合框架。

2.spring中的事务管理,首先事务的基本概念就是一处报错,全部回滚。这也是spring事务管理的基本作用。

3.spring事务管理分为xml 跟 注解

案例:

(1)实体类Employee.java

package com.gb.pojo;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Component;
@Component("emp")
public class Employee {

private Integer id;
private String realName;
private SexEnum sex;
private Date birthday;
private String mobile;
private String email;
private String positon;
private String note;

private WorkCard workCard;
private List<EmployeeTask> taskList;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getRealName() {
    return realName;
}

public void setRealName(String realName) {
    this.realName = realName;
}

public SexEnum getSex() {
    return sex;
}

public void setSex(SexEnum sex) {
    this.sex = sex;
}

public Date getBirthday() {
    return birthday;
}

public void setBirthday(Date birthday) {
    this.birthday = birthday;
}

public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPositon() {
    return positon;
}

public void setPositon(String positon) {
    this.positon = positon;
}

public String getNote() {
    return note;
}

public void setNote(String note) {
    this.note = note;
}

public WorkCard getWorkCard() {
    return workCard;
}

public void setWorkCard(WorkCard workCard) {
    this.workCard = workCard;
}

public List<EmployeeTask> getTaskList() {
    return taskList;
}

public void setTaskList(List<EmployeeTask> taskList) {
    this.taskList = taskList;
}

@Override
public String toString() {
    return "Employee [id=" + id + ", realName=" + realName + ", sex=" + sex
            + ", birthday=" + birthday + ", mobile=" + mobile + ", email="
            + email + ", positon=" + positon + ", note=" + note
            + ", workCard=" + workCard + ", taskList=" + taskList + "]";
}
    }

(2)mapper接口类:EmployeeMapper -----这里主要测试update方法

package com.gb.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.gb.pojo.EmpParames;
import com.gb.pojo.Employee;

public interface EmployeeMapper {
Employee findEmployeeById(Integer id);

/**
 * 根据名字查询员工,名字可以传,也可以不传,当传时,名字需要作为条件
 * 当不传时(empName为null或者空串),就不需要名字作为条件
 * @param empName
 * @return
 */
List<Employee> findEmployeeByName(String empName);
  //    List<Employee> findEmployeeByName(@Param("ename") String empName);

/**
 * 根据姓名与电话查询员工
 * 姓名可以传也可以不传
 * 电话可以传也可以不传,如果传的话,要以所传的内容作为开头
 * @param empPara
 * @return
 */
List<Employee> findEmployeeByBean(EmpParames empPara);

/**
 * 根据id,name,tel进行查询
 * 如果id不为0或者null,则根据id查询
 * 如果id为0或为null且name不为null与空串,则根据name进行模糊查询
 * 如果以上都不符合,那么就查询出电话不为空的员工
 * 
 * @param id
 * @param name
 * @param tel
 * @return
 */
List<Employee> findEmployeeChoose(@Param("id") Integer id,@Param("name") String name);

/**
 * 更新员工信息
 * @param emp
 * @return
 */
int updateEmployee(Employee emp);

/**
 * 查询所有员工编号在集合idList中的员工信息
 * @param idList
 * @return
 */
List<Employee> findEmployeeInList(List<Integer> idList);

/**
 * 判断出入的字符串是否是'X',
 * 如果是'X'的话,就查询姓名包含X的员工信息,
 * 否则就查询所有员工信息
 * @param str
 * @return
 */
List<Employee> findEmployeeByStringEqual(String str);}

(3)EmployeeMapper.xml配置文件: 自行甄别

<?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.gb.mapper.EmployeeMapper">
<resultMap type="emp" id="employee">
    <id column="id" property="id" />
    <result column="real_name" property="realName" />
    <result column="sex" property="sex" />
    <result column="birthday" property="birthday" />
    <result column="mobile" property="mobile" />
    <result column="email" property="email" />
    <result column="positon" property="positon" />
    <result column="note" property="note" />
    <association property="workCard" column="id"
        select="com.gb.mapper.WorkCardMapper.findWorkCardByEmpid"></association>
    <collection property="taskList" column="id"
        select="com.gb.mapper.EmployeeTaskMapper.findEmployeeTaskByEmpId"></collection>
    <discriminator javaType="int" column="sex">
        <case value="1" resultMap="maleEmployee"></case>
        <case value="2" resultMap="femaleEmployee"></case>
    </discriminator>

</resultMap>
<resultMap type="feemp" id="femaleEmployee" extends="employee">
    <association property="femaleHealthForm" column="id"
        select="com.gb.mapper.FemaleHealthFormMapper.findFemaleHfByEmpId"></association>
</resultMap>

<resultMap type="maemp" id="maleEmployee" extends="employee">
    <association property="maleHealthForm" column="id"
        select="com.gb.mapper.MaleHealthFormMapper.findMaleHfByEmpId"></association>
</resultMap>



<select id="findEmployeeById" parameterType="int" resultMap="employee">
    select * from t_employee where id=#{id}
</select>

<select id="findEmployeeByName" parameterType="string"
    resultMap="employee">
    select * from t_employee
    <where>
        <if test=" _parameter!=null and _parameter!=''">
            and real_name=#{empName}
        </if>
    </where>
    <!-- <if test=" ename!=null and ename!=''"> and real_name=#{ename} </if> -->
</select>

<select id="findEmployeeByBean" parameterType="com.gb.pojo.EmpParames"
    resultMap="employee">

    select * from t_employee
    <trim prefix="where" prefixOverrides="and">
        <if test=" name!=null and name!=''">
            and real_name like concat('%',#{name},'%')
        </if>
        <if test=" tel!=null and tel!=''">
            and mobile like concat(#{tel},'%')
        </if>
    </trim>
</select>

<select id="findEmployeeChoose" resultMap="employee">

    select * from t_employee
    where 1=1
    <choose>
        <when test="id!=null and id!=0">
            and id=#{id}
        </when>
        <when test="name!=null and name!=''">
            and real_name like concat('%',#{name},'%')
        </when>
        <otherwise>
            and mobile is not null
        </otherwise>
    </choose>
</select>

<update id="updateEmployee" parameterType="emp">
    update t_employee
    <set>
        <if test=" realName!=null and realName!=''">
            real_name= #{realName},
        </if>
        <if test=" sex!=null and sex!=0">
            sex=#{sex},
        </if>

        <if test=" birthday!=null and birthday!=''">
            birthday=#{birthday},
        </if>
        <if test=" mobile!=null and mobile!=''">
            mobile=#{mobile},
        </if>

        <if test=" email!=null and email!=''">
            email=#{email},
        </if>
        <if test=" positon!=null and positon!=''">
            positon=#{positon},
        </if>
        <if test=" note!=null and note!=''">
            note=#{note}
        </if>
    </set>
    where id=#{id}
</update>


<select id="findEmployeeInList" parameterType="list" resultMap="employee">
    select * from t_employee
    where id in
    <foreach collection="list" index="i" item="val" open="("
        separator="," close=")">
        #{val}
    </foreach>
</select>

<select id="findEmployeeByStringEqual" parameterType="string"
    resultMap="employee">
    <bind name="realName" value="'%' + _parameter + '%'"/>
    
    select * from t_employee
    <where>
        <if test=" _parameter=='X'.toString()">
             real_name  like #{realName}
        </if>
    </where>
</select>
</mapper>

(4) 向上写 Service层,EmployeeService.java

package com.gb.service;

import com.gb.pojo.Employee;

public interface EmployeeService {
Employee findEmployeeById(Integer id);
int updateEmployee(Employee emp);
}

service接口类实现类:EmployeeServiceImpl.java

package com.gb.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.gb.mapper.EmployeeMapper;
import com.gb.pojo.Employee;

@Component
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
private EmployeeMapper employeeMapper;


public void setEmployeeMapper(EmployeeMapper employeeMapper) {
    this.employeeMapper = employeeMapper;
}



@Transactional(readOnly=true,propagation=Propagation.REQUIRED, isolation=Isolation.READ_UNCOMMITTED)
@Override
public Employee findEmployeeById(Integer id) {
    return employeeMapper.findEmployeeById(id);
}


@Transactional
@Override
public int updateEmployee(Employee emp) {
    return employeeMapper.updateEmployee(emp);
}
    }

(5):Controller层, EmployeeController.java

package com.gb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gb.pojo.Employee;
import com.gb.service.EmployeeService;

@Component
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

public void setEmployeeService(EmployeeService employeeService) {
    this.employeeService = employeeService;
}


public Employee getEmployeeById(Integer id) {
    return employeeService.findEmployeeById(id);
}

public int updateEmployee(Employee emp){
    return employeeService.updateEmployee(emp);
}
    }

(6)spring-context.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:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/tx 
 http://www.springframework.org/schema/tx/spring-tx.xsd
 http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop.xsd
 ">

<context:component-scan base-package="com.gb"></context:component-scan>

<tx:annotation-driven transaction-manager="transactionManager"/>


<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver" />
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mbdb" />
    <property name="user" value="root" />
    <property name="password" value="" />
    <!-- 关键配置 -->
    <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
    <property name="initialPoolSize" value="3"></property>
    <!--连接池中保留的最小连接数。Default: 2 -->
    <property name="minPoolSize" value="2"></property>
    <!--连接池中保留的最大连接数。Default: 15 -->
    <property name="maxPoolSize" value="15"></property>
    <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
    <property name="acquireIncrement" value="3"></property>
    <!-- 性能配置 -->
    <!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 
        0 -->
    <property name="maxStatements" value="8"></property>
    <!-- maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 
        0 -->
    <property name="maxStatementsPerConnection" value="5"></property>
    <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
    <property name="maxIdleTime" value="1800"></property>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>


<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.gb.mapper" />
</bean>

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


<!-- 事务配置 -->
<!-- <tx:advice id="tx_advice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="find*" read-only="true" isolation="DEFAULT"
            propagation="REQUIRED" />
        <tx:method name="select*" read-only="true" isolation="DEFAULT"
            propagation="REQUIRED" />
        <tx:method name="get*" read-only="true" isolation="DEFAULT"
            propagation="REQUIRED" />
        <tx:method name="add*" />
        <tx:method name="insert*" />
        <tx:method name="save*" />
        <tx:method name="del*" />
        <tx:method name="remove*" />
        <tx:method name="update*" />
    </tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut expression="execution(* com.gb.service.*.*(..))"
id="tx_pc" />
<aop:advisor advice-ref="tx_advice" pointcut-ref="tx_pc"/>
</aop:config> -->
</beans>

(7)mybatis-config.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>



<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>

<typeAliases>
<typeAlias type="com.gb.handler.SexEnumHandler" alias="seh"/> 
<typeAlias type="com.gb.pojo.SexEnum" alias="se"/>
<typeAlias type="com.gb.pojo.Task" alias="task"/>
<typeAlias type="com.gb.pojo.WorkCard" alias="workcard"/>
<typeAlias type="com.gb.pojo.EmployeeTask" alias="employeeTask"/>
<typeAlias type="com.gb.pojo.FemaleHealthForm" alias="fhf"/>
<typeAlias type="com.gb.pojo.MaleHealthForm" alias="mhf"/> 
<typeAlias type="com.gb.pojo.Employee" alias="emp"/>
<typeAlias type="com.gb.pojo.FemaleEmployee" alias="feemp"/>
<typeAlias type="com.gb.pojo.MaleEmployee" alias="maemp"/>
</typeAliases>

<typeHandlers>
<typeHandler handler="seh" javaType="se" jdbcType="INTEGER"/>
</typeHandlers>
</configuration>

(8)main方法

    private static void updateEmployee(){
    AbstractApplicationContext ac = new ClassPathXmlApplicationContext("spring-context.xml");

    EmployeeController ec = ac.getBean(EmployeeController.class);
   //       Employee emp = ec.getEmployeeById(2);
    
    Employee emp = (Employee) ac.getBean("emp");
  //        System.out.println(emp.getRealName());
    
    
    emp.setId(1);
    emp.setRealName("tuyiuouoih");
    
    int count = ec.updateEmployee(emp);
    System.out.println(count + "======================================");
    ac.close();
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,654评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,809评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,630评论 18 399
  • 还有二十天结束了,应该会有一篇感受,大四下真的好多意料之外。
    孙十三燕窝哥阅读 154评论 0 1
  • 这不是我第一次写文,最早的一篇文可以追溯到初中, 在哪充满着想想的日子,在哪儿每天都做不同的梦的日子,在笔记本上记...
    猫侈愚_丹冉冉阅读 583评论 0 1