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();
}