一、项目构成
1、新建maven项目
2、加入maven依赖
1)spring依赖;spring-context
2)spring的事务依赖;spring-tx
3)spring集成jdbc依赖;spring-jdbc
4)mysql驱动;mysql-connector-java
5)mybatis依赖;mybatis
6)mybatis和spring集成的依赖:spring官方提供,用来在spring项目中创建mybatis的
sqlSessionFactory对象,dao对象;mybatis-spring
7)druid连接池;druid
3、创建实体类
4、创建dao接口和mapper文件
5、创建mybatis配置文件
6、创建Service接口和实现类,属性是dao
6、创建spring配置文件:声明mybatis对象交给spring
1)数据源;
2)SqlSessionFactory;
3)Dao对象;
4)声明自定义的service;
6、创建测试类,获取service对象,通过service对象调用dao完成数据库的访问
二、项目搭建
1、创建maven项目的module,选择quickstart骨架
2、pom文件添加所有依赖
<dependencies>
<!-- 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring核心依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- spring事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- spring连接jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- spring集成jdbc依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!-- 德鲁伊连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>
3.pom文件添加资源文件编译路径
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>false</filtering>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
4.创建所有的包与文件
main目录下创建resources目录,然后添加mybatis配置文件mybatis.xml和spring配置文件spring.xml
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>
<!--设置实体类的别名-->
<typeAliases>
<!--对于每个实体类单独配置别名(不区分大小写)-->
<!--<typeAlias alias="student" type="com.fssx.domain.Student"/>-->
<!--对于整个包进行配置,所有的实体类别名为类名(不区分大小写-->
<package name="com.fssx.domain"/>
</typeAliases>
<!-- 设置环境配置,default为不指定时的默认配置-->
<!--指定mybatis加载mapper映射文件的地址-->
<mappers>
<!--对于单个xml文件的相对路径进行配置-->
<!--<mapper resource="org/example/dao/StudentDao.xml"/>-->
<!--对于整个包进行配置,加载包内所有的mapper文件-->
<package name="com.fssx.dao"/>
</mappers>
</configuration>
spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--注册Druid连接池-->
<bean id="MyDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!--通过set注入给连接池赋值-->
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="maxActive" value="20"/>
</bean>
<!--创建SqlSessionFactoryBean,引入连接池和mybatis配置文件-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="MyDataSource"/>
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!--创建MapperScannerConfigurer,引入SqlSessionFactoryBean,和配置的dao包地址-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.fssx.dao"/>
</bean>
</beans>
java目录下创建实体类包domain,添加实体类Student;
服务类包service,添加服务类接口StudentService,实现接口创建StudentServiceImpl实现类;
数据库接口包dao,创建接口StudentDao,映射文件StudentDao.xml
Student实体类,省略set和toString方法
package com.fssx.domain;
import org.springframework.stereotype.Repository;
// 使用注解将实体类加载到spring中
@Repository
public class Student {
private String name;
private String sex;
private int age;
}
StudentDao接口
package com.fssx.dao;
import com.fssx.domain.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
Student queryStudent(String name);
List<Student> queryStudents();
}
StudentDao映射文件
<?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.fssx.dao.StudentDao">
<!--#{}占位符,用来指代传入的参数名-->
<insert id="insertStudent">
insert into student value (#{name},#{sex},#{age});
</insert>
<!--返回值类型为Student,要写全限定名称,如果在mybatis.xml中配置了typeAliases别名,这里可以简写类名-->
<select id="queryStudent" resultType="com.fssx.domain.Student">
select * from student where name = #{name};
</select>
<!--这里可以简写类名-->
<select id="queryStudents" resultType="Student">
select * from student;
</select>
</mapper>
StudentService接口
package com.fssx.service;
import com.fssx.domain.Student;
import java.util.List;
public interface StudentService {
void test();
int insertStudent(Student student);
Student queryStudent(String name);
List<Student> queryStudents();
}
StudentServiceImpl实现类
package com.fssx.service.impl;
import com.fssx.dao.StudentDao;
import com.fssx.domain.Student;
import com.fssx.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service(value = "studentService")
public class StudentServiceImpl implements StudentService {
@Resource
private StudentDao studentDao;
@Override
public int insertStudent(Student student) {
return studentDao.insertStudent(student);
}
@Override
public Student queryStudent(String name) {
return studentDao.queryStudent(name);
}
@Override
public List<Student> queryStudents() { return studentDao.queryStudents(); }
}
AppTest测试类
package com.fssx;
import com.fssx.domain.Student;
import com.fssx.service.StudentService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppTest {
@Test
public void Test() {
String config = "spring.xml";
// 通过spring配置文件加载spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(config);
// 通过容器获取对象student,studentService
Student student = (Student) context.getBean("student");
StudentService studentService = (StudentService) context.getBean("studentService");
student.setName("王二");
student.setSex("男");
student.setAge(22);
// 使用Service接口执行数据库操作
studentService.insertStudent(student);
System.out.println(studentService.queryStudent("李四"));
System.out.println(studentService.queryStudents());
}
}
5.运行结果
程序输出
Student{name='李四', sex='女', age=21}
[Student{name='李四', sex='女', age=21}, Student{name='王三', sex='男', age=14}, Student{name='王二', sex='男', age=22}]
数据库对比前后
三、Spring事务
1、数据库事务隔离级别
原理参考
https://blog.youkuaiyun.com/qq_33967820/article/details/119674571
ISOLATION_DEFAULT 使用后端数据库默认的隔离级别
ISOLATION_READ_UNCOMMITTED 允许读取尚未提交的更改。可能导致脏读、幻读或不可重复读。
ISOLATION_READ_COMMITTED (Oracle 默认级别)允许从已经提交的并发事务读取。可防止脏读,但幻读和不可重复读仍可能会发生。
ISOLATION_REPEATABLE_READ (MYSQL默认级别)对相同字段的多次读取的结果是一致的,除非数据被当前事务本身改变。可防止脏读和不可重复读,但幻读仍可能发生。
ISOLATION_SERIALIZABLE 完全服从ACID的隔离级别,确保不发生脏读、不可重复读和幻影读。这在所有隔离级别中也是最慢的,因为它通常是通过完全锁定当前事务所涉及的数据表来完成的。
2、事务传播机制
常用机制
PROPAGATION_REQUIRED
Spring默认的传播机制,能满足绝大部分业务需求,如果外层有事务,则当前事务加入到外层事务,一块提交,一块回滚。如果外层没有事务,新建一个事务执行
PROPAGATION_REQUIRES_NEW
该事务传播机制是每次都会新开启一个事务,同时把外层事务挂起,当当前事务执行完毕,恢复上层事务的执行。如果外层没有事务,执行当前新开启的事务即可
PROPAGATION_SUPPORT
如果外层有事务,则加入外层事务,如果外层没有事务,则直接使用非事务方式执行。完全依赖外层的事务,例如查询操作
PROPAGATION_NOT_SUPPORT
该传播机制不支持事务,如果外层存在事务则挂起,执行完当前代码,则恢复外层事务,无论是否异常都不会回滚当前的代码
PROPAGATION_NEVER
该传播机制不支持外层事务,即如果外层有事务就抛出异常
PROPAGATION_MANDATORY
与NEVER相反,如果外层没有事务,则抛出异常
PROPAGATION_NESTED
该传播机制的特点是可以保存状态保存点,当前事务回滚到某一个点,从而避免所有的嵌套事务都回滚,即各自回滚各自的,如果子事务没有把异常吃掉,基本还是会引起全部回滚的。
3、Spring事务使用方法
1、使用注解配置
添加xml配置
<!--声明事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--链接的数据库,指定数据源-->
<property name="dataSource" ref="MyDataSource"/>
</bean>
<!--开启事务注解驱动,创建代理对象-->
<tx:annotation-driven transaction-manager="transactionManager"/>
@Transactional()
propagation 设置事务传播属性,默认值为PROPAGATION_REQUIRED
isolation 设置事务隔离级别,默认值为Isolation.DEFAULT
readOnly 设置该方法是否对数据库的操作为只读,默认为false
timeout 设置操作与数据库的连接时限,单位为秒,类型为int,默认为-1没有时限
rollbackFor 需要回滚的异常类,类型为Class[],默认值为空数组,若只有一个异常类可以不使用数组
rollbackForClassName 需要回滚的异常类,类型为String[],默认值为空数组,若只有一个异常类可以不使用数组
noRollbackFor 不需要回滚的异常类,类型为Class[],默认值为空数组,若只有一个异常类可以不使用数组
noRollbackForClassName 不需要回滚的异常类,类型为String[],默认值为空数组,若只有一个异常类可以不使用数组
@Transactional若用在方法上,只能是public方法,非public方法添加不会报错但是也不会生效,spring会自动忽略掉所有非public方法上的@Transactional
2、使用AspectJ配置注解
添加spring-ascpects依赖
添加事务配置
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--链接的数据库,指定数据源-->
<property name="dataSource" ref="MyDataSource"/>
</bean>
<!--开启事务注解驱动,创建代理对象-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<tx:advice id="myAdvice">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="servicePt" expression="execution(* *..service..*.*(..))"/>
<aop:advisor advice-ref="myAdvice" pointcut-ref="servicePt"/>
</aop:config>