1、Spring
1.1简介
- 2002,首次退出来Spring框架的雏形:interface21框架
- Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,与2004年3月24日,发布了1.0正式版
- Rod Johnson,Spring framework创始人,著名作者。
- spring理念:是现有的技术更加容易使用,本身是一个大杂烩
官网地址:
https://spring.io/projects/spring-framework
官方下载地址
https://repo.spring.io/ui/native/release/org/springframework/spring/
对应jar包的导入
org.springframework
spring-webmvc
5.3.22
1.2优点
- Spring是一个开源的免费的框架(容器)
- Spring是一个轻量级的,非入侵式的框架(不会使项目因为导入改jar包而导致项目不能运行)
- 控制反转(IOC),面向切面编程(AOP)
- 支持事物的处理,对框架整合的支持
总结一句话:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!
1.3组成
1.4拓展
在Spring的官网有这个介绍:现代化的Java开发!说白了就是基于Spring的开发
- Spring Boot
- 一个快速开发的脚手架(用了SpringBoot之后就可以根据一个配置就可以开发一个网站)
- 基于SpringBoot可以快速的开发单个微服务
- 约定大于配置
- Spring Cloud
- SpringCloud是基于SpringBoot实现的
因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用
弊端:发展了太久之后,违背了原来的理念,配置十分繁琐,人称:”配置地狱”
2.IOC理论推导
2.1以前写项目的过程
- UserDao接口
package com.tang.dao;
public interface UserDao {
public void getUser();
}
- UserDaoImpl实现类
package com.tang.dao;
public class UserDaoImpl implements UserDao{
public void getUser() {
System.out.println("默认UserDao加载数据");
}
}
UserMysqlDaoImpl实现类
public class UserMysqlDaoImpl implements UserDao{
public void getUser() {
System.out.println("Mysql获取数据");
}
}
- UserService业务接口
package com.tang.service;
public interface UserService {
public void getUser();
}
- UserServiceImpl业务实现类
package com.tang.service;
import com.tang.dao.UserDao;
import com.tang.dao.UserDaoImpl;
public class UserServiceImpl implements UserService{
//private UserDao userDao = new UserDaoImpl();
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
//利用set进行动态实现指的注入
public void getUser() {
userDao.getUser();
}
}
模拟的用户层
public class Mytest {
@Test
public void test(){
//用户实体调用的是业务层,dao层他们不需要接触
UserService userService = new UserServiceImpl();
//控制权交给用户,用户想调用谁的实现类就直接new即可
((UserServiceImpl)userService).setUserDao(new UserMysqlDaoImpl());
userService.getUser();
}
}
测试结果
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码,如果程序代码量十分大,修改一次的成本代价十分昂贵
我们使用一个set接口实现,每当用户更改之后,不用在业务层去修改源码,只需要在用户层,根据用户所需调用相应的service层然后service层去调用dao层的代码
public class UserServiceImpl implements UserService{
//以前就需要在业务层,每当用户改变之后new 的实现类也必须随之发生变化,加了个set之后就可以在用户层根据所需通过service间接使用所需要的用户层的实现类
//private UserDao userDao = new UserDaoImpl();
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
//利用set进行动态实现指的注入
public void getUser() {
userDao.getUser();
}
}
- 之前,程序是主动创建对象,控制权在程序猿手上
- 使用set注入后,程序不再具有主动性,而是变成了被动的接收对象
这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了,系统的耦合性大大降低,可以更加专注在业务的是线上,这是IOC的原型
2.2.IOC本质
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
3.HelloSpring
bean.xml创建方式
实体类User
package com.tang.pojo;
public class Hello {
private String str;
public Hello() {
}
public Hello(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
beans.xml
测试代码
public class MyTest {
@Test
public void test(){
//获取Spring的上下文对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在Spring中管理了,我们要使用,直接去里面取出来就可以了
Hello hello = (Hello) context.getBean("hello");//这里就相当于new了一个对象
System.out.println(hello.toString());
}
}
运行结果图
如果运行之后报这个错IOException parsing XML document from class path resource [beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [beans.xml] cannot be opened because it does not exist
可以将该项目的pom文件的打包方式设置为jar即可解决此问题,问题出现原因就是在target中没有beans.xml文件导致
【思考问题?】
- Hello对象是谁创建的?
hello对象是由Spring创建的 - Hello对象的属性是怎么设置的?
- hello对象的属性是由Spring容器设置的
这个过程就叫控制反转:
控制:谁来控制对象的创建,传统应用程序的对象是有程序本身控制创建的,使用Spring后,对象是由Spring来创建的
反转:程序本身不创建对象,而变成不被动的接收对象
依赖注入:就是利用set方法来进行注入的
IOC是一种编程思想,由主动地编程变成被动的接收
可以通过new ClassPathXmlApplicationContext去浏览以下底层的源码
OK,到了现在,我们彻底不用在程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC一句话搞定:对象有Spring来创建,管理,装配!
4.IOC创建对象的方式
4.1使用无参构造创建对象,默认
beans.xml
测试代码
@Test
public void UserTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
}
测试结果
4.2假设我们要使用了有参构造
下标赋值
通过类型创建,不建议使用
通过参数名来设置
5.Spring配置
5.1别名
@Test
public void UserTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("fasdagsd");
System.out.println(user.toString());
}
5.2Bean的配置
5.3Import
这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并一个
假设,现在项目中有多个人开发(张三,李四,王五),这三个人复制不同的类开发,不同的类需要注册在不同的Bean中,我们可以利用import将多诱人的beans.xml合并为一个总的
使用的时候,直接使用总的配置就可以了
项目结构图
application.xml
6.DI依赖注入
6.1Set方式注入(重点)
- 依赖注入:Set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器注入
(1)环境搭建
复杂类型
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
真实测试对象
public class Student {
private String name;
private Address address;
private String[] books;
private List hobbys;
private Map card;
private Set games;
private String wife;
private Properties info;
//get,set方法这里就不写上了,可以自己写上
}
beans.xml
测试类
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
完善注入信息
beans.xml
红楼梦
三国
水浒传
听歌
敲代码
看电影
LOL
COC
BOB
20220140
男
20220140
测试结果
7.Bean的自动装配
7.1自动装配
自动装配是Spring满足Bean依赖的一种方式
spring会在上下文中自动寻找,并自动给Bean装配属性
在Spring中有三种装配的方式
- 在xml中显示的配置
- 在Java中显示配置
- 隐式的自动装配Bean【重要】
7.2测试
环境搭建:一个人有两个宠物
ByName自动装配
ByType自动装配
小结:
- byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
- byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
7.3使用注解实现自动装配
要使用注解须知:
- 导入约束:context约束
- 配置注解的支持
在实体类上使用注解即可
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
测试代码
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getDog().shot();
people.getCat().shot();
}
运行结果图
@Autowired
直接在属性山使用即可,也可以在set方法上使用
使用@Autowired我们可以不用编写set方法了,前提是你这个自动装的属性在IOC(Spring)容器中存在,且符合名字byname
8.使用注解开发
在Spring4之后,要使用注解开发,必须要保证aop的包导入了
使用注解需要导入context约束,增加注解的支持
8.1.属性如何注入
//等价于
//@Component组件,放在类上,说明这个类被Spring管理了,就是bean
@Component
public class User {
// public String name ="唐昊";
//相当于
@Value("唐昊")//给name赋值
public String name;
}
8.2衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层
- dao【@Repository】
- service【@Service】
- controller【@Controller】
这四个注解功能都是一样的,都是代表某个类注册到Spring中,装配Bean
8.3小结
xml与注解:
- xml更加万能,适用于任何场合!维护简单方便
- 注解不是自己的类使用不了,维护相对复杂
最佳实践:
- xml用来管理bean
- 注解只负责完成属性的注入
- 我们在使用的过程中,只需要注意一个问题,必须让注解生效,就需要开启注解的支持
9.使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给java来做
JavaConfig是Spring的一个子项目,在Spring4之后,他就成为了一个核心功能
User实体类代码
//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
@Value("唐三")//将name的值设置为唐三
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Config类
/*
* 这个也会被Spring容器托管,注册倒容器中,因为他本爱就是一个@Component
* @Confguration代表这是一个配置类,就是我们之前看的beans.xml*/
@Configuration
@Component("com.tang.pojo")
public class TangConfig {
//注册一个bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签的id属性
//这个方法的返回值,就相当于bean标签中class属性
@Bean
public User getUser(){
return new User();//就是要返回要注入到bean的对象
}
测试类
public class MyTest {
@Test
public void test(){
//如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文
// 来获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(TangConfig.class);
User getUser = context.getBean("getUser", User.class);//取得getUser是TangConfig中经过Bean注册过的
System.out.println(getUser.getName());
}
这种纯java的配置方式,在SpringBoot中随处可见
10.代理模式
为什么要学习代理模式? 因为这就是SpringAOP的底层!【SpringAOP和SpringMVC面试必问】
代理模式的分类:
- 静态代理
- 动态代理
10.1静态代理
角色分析:
- 存在一个抽象角色(比如上图中介和房东共同完成租房这个事件):一般会使用接口或者抽象类来解决
- 真是角色:被代理的角色
- 代理角色:代理真是角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人
代码步骤:
①.接口
//租房
public interface Rent {
public void rent();
}
②.真实角色(房东)
//房东
public class Host implements Rent {
public void rent(){
System.out.println("房东要出租房子");
}
}
③.代理角色
//代理(中介帮房东出租房子)
public class Proxy implements Rent{
private Host host;//中介得找到房东
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
public void rent() {
host.rent();
seeHouse();
contract();
fees();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
//签合同
public void contract(){
System.out.println("签租赁合同");
}
//收中介费
public void fees(){
System.out.println("收中介费");
}
}
④.客户访问dialing角色
public class Client {
public static void main(String[] args) {
Host host = new Host();//房东要出租房子
//中介帮房东出租房子,但是dialing角色一般会有一些附属操作
Proxy proxy = new Proxy(host);
//你不用面对房东,直接找中介租房
proxy.rent();
}
}
代理模式的好处
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共业务就交给代理角色!实现业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真是角色就会产生一个代理角色;代码量会翻倍-开发效率低
10.2加深理解
目的:在每次调用增删改查的时候打印一个日志,表明当前调用的是哪个操作,在公司里在原来的代码上修改是大忌,这时就可以采用代理模式来实现
UserService接口
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
UserServiceImpl代码
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("添加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void query() {
System.out.println("查询了一个用户");
}
}
UserServiceProxy代理代码
public class UserServiceProxy implements UserService{
private UserServiceImpl userServiceimpl;
public void setUserServiceimpl(UserServiceImpl userServiceimpl) {
this.userServiceimpl = userServiceimpl;
}
public void add() {
log("add");
userServiceimpl.add();
}
public void delete() {
log("delete");
userServiceimpl.delete();
}
public void update() {
log("update");
userServiceimpl.update();
}
public void query() {
log("query");
userServiceimpl.query();
}
public void log(String name){
System.out.println("[debug]调用了"+name+"方法");
}
}
测试代码
public class MyTest {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy userServiceProxy = new UserServiceProxy();
userServiceProxy.setUserServiceimpl(userService);
userServiceProxy.add();
}
}
测试结果
10.3动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的
- 动态dialing分为两大类:基于接口的代理,基于类的动态代理
- 基于接口—JDK动态代理
- 基于类:cglib
- java字节码实现:javAssist
需要了解两个类:Proxy:代理,InvocationHandler:调用处理程序
租房接口类
//租房
public interface Rent {
public void rent();
}
真实角色Host房东
//房东
public class Host implements Rent {
public void rent(){
System.out.println("房东要出租房子");
}
}
动态生成代理ProxyInvocationHandler
//等会这里会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(rent, args);
contract();
return result;
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
//签合同
public void contract(){
System.out.println("签租赁合同");
}
}
用户类
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色:现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理鴃舌来处理我们要调用的接口对象
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();//这里的Proxy就是动态生成的,我们并没有写
proxy.rent();
}
}
测试结果
将ProxyInvocationHandler提取为工具类,并实现增删改查的时候打印日志的操作
项目结构图
ProxyInvocationHandler代码
package com.tang.demo04;
import com.tang.demo03.Rent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//等会我们会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void settarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());//得到当前执行方法的名字
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(target, args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
测试代码
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色,不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.settarget(userService);//设置要代理的对象
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.delete();
}
}
测试结果
动态代理的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共业务就交给代理角色!实现业务的分工
- 公共业务发生扩展的时候,方便集中管理
*一个动态代理类处理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现类同一个接口即可
11.AOP
11.1什么是AOP
在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2AOP在Spring中的作用
提供声明式事务;允许用户自定义切面
11.3使用Spring实现Aop
【重点】使用AOP织入,需要导入一个依赖包
org.aspectj
aspectjweaver
1.9.9.1
①使用Spring的API接口
UserService接口
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
UserServiceImpl代码
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("添加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void select() {
System.out.println("查询了一个用户");
}
}
Log代码
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
AfterLog代码
public class AfterLog implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回值结果为:"+returnValue);
}
}
applicationContext.xml代码
测试代码
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.delete();
}
}
测试结果
②自定义来实现AOP
diy下的DiyPointCut类的代码
public class DiyPointCut {
public void before(){
System.out.println("=======方法执行前======");
}
public void after(){
System.out.println("=======方法执行后======");
}
}
applicationContext.xml核心代码
其它代码同方式一使用Spring的API接口代码相同就不在写了
测试结果
③使用注解来实现AOP
beas.xml核心代码
AnnotationPointCut代码
//方式三:使用注解方式实现AOP
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.tang.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=======方法执行前======");
}
@After("execution(* com.tang.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("=========方法执行后==========");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.tang.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable{
System.out.println("环绕前");
Signature signature = jp.getSignature();//获得签名
System.out.println("signature:"+signature);
Object proceed = jp.proceed();//执行方法
System.out.println("环绕后");
System.out.println(proceed);
}
}
测试结果
12.整合Mybatis
12.1步骤
①导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关的
- aop织入
- mybatis-spring
②编写配置文件
③测试
12.2回忆mybatis
步骤:
- 编写实体类
@Data
public class User {
private int id;
private String name;
private String pwd;
}
- 编写核心配置文件
- 编写接口
UserMapper接口代码
public interface UserMapper {
public List selectUser();
}
- 编写mapper.xml
select * from mybatis.user
- 测试
public class MyTest {
@Test
public void test() throws IOException {
String resources ="mybatis-config.xml";
InputStream in = Resources.getResourceAsStream(resources);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List userList = mapper.selectUser();
for (User user : userList) {
System.out.println(user);
}
}
}
测试结果:
12.2Mybatis-spring
项目结构图
①编写数据源配置
②sqlSessionFactory
③sqlSessionTemplate
④需要给接口加实现类
public class UserMapperImpl implements UserMapper{
//我们的所有操作,都使用sqlSession来执行,在原来,现在都使用SqlSessionTemplate;
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
⑤将自己写的实现类,注入到Spring中
⑥测试使用即可
public class MyTest {
@Test
public void test() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
List userList = userMapper.selectUser();
for (User user : userList) {
System.out.println(user);
}
}
}
测试结果
13、声明事务
13.1回顾事务
- 把一组业务当成一个业务来做,要么都成功,要么都失败
- 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎
- 确保完整性和一致性
事务ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器其中
项目结构图
目的:测试在一组事件中进行增加和删除操作,删除失败,添加成功,该事件不属于事务,因为事务是要么都成功要么都失败
注意:我下面的删除语句delete多个s是因为想实现上诉步骤使删除失败,添加成功
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
UserMapper接口
public interface UserMapper {
public List selectUser();
//添加一个用户
public int addUser(User user);
//删除一个用户
public int deleteUser(int id);
}
mybatis-config.xml
spring-dao.xml
UserMapper.xml
select * from mybatis.user
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
deletes from user where id=#{id}
UserMapperImpl
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
public List selectUser() {
User user = new User(7,"Twq小王","2131231");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(7);
return mapper.selectUser();
}
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
applicationContext.xml
测试结果图
13.2使用声明式事务
对于上诉例子,如果想开启事务使得插入和删除为一个事务,也即删除和添加要么都成功,要么都失败,需要进行以下步骤:
- 配置声明式事务(spring-dao.xml文件中配置)
*配置事务通知
*配置事务切入
以上配置好之后,继续测试发现当删除没成功的时候,插入也失败,符合事务的要求
只有当删除和插入都成功,该事务才算成功
Original: https://www.cnblogs.com/twq46/p/16580569.html
Author: 剑断青丝ii
Title: Spring5完整版详解
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/591102/
转载文章受原作者版权保护。转载请注明原作者出处!