title: Spring5基础
tags: [Spring5]
index_img: /img/page_banner/2.jpg
banner_img: /img/page_banner/2.jpg
date: 2021-10-13 17:00:00
Spring5是学习开发框架的必经之路,学会Spring5才便于进阶。
全文关于入门案例、IOC和Bean的配置、AOP、JDBC-Template、Spring事务。
Spring5基础
入门案例:
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置User对象创建-->
<bean id="user" class="spring_learn.User"></bean>
</beans>
test:
public class testspring5 {
@Test
public void testAdd(){
//1.加载spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
//2.获取配置创建的对象
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
}
1.IOC 容器和 Bean 的配置
1.1 IOC(Inversion of Control):控制反转
什么是IOC?
(1)把对象创建和对象之间的调用过程,交给spring管理。
(2)使用IOC目的:为了耦合度降低
IOC底层原理?
xml解析、工厂模式、反射
IOC(接口)?
1.IOC思想基于IOC容器完成,IOC容器底层就是对象工厂。
2.Spring提供IOC容器实现两种方式:(两个接口)
(1)BeanFactory :IOC容器基本实现,是Spring内部的使用接口,开发人员一般不使用。
-
加载配置文件时不会创建对象,在获取(使用)对象时才会去创建对象。
(2)ApplicationContext : BeanFactory接口的子接口,提供更多更强大的功能。
-
加载配置文件时就会创建对象
1.2 IOC操作 Bean管理
1.什么是Bean管理?
Bean管理指的是两个操作: Spring创建对象 和 Spring注入属性
2.Bean管理操作有两种方式
(1) 基于xml配置文件方式存在
xml配置对象创建:
<bean id="user" class="spring_learn.User"></bean>
在spring配置文件中,使用bean标签,在标签里添加对应属性,就可以实现对象创建。
bean标签中有很多属性,介绍一下常用的属性:
*id属性 - 唯一标识
*class属性 - 类全路径
创建对象时,默认执行无参构造方法。
xml方式注入属性:
(1) DI: 依赖注入,就是注入属性
第一种注入方法:使用set方法进行注入
user类中:
public class Book {
private String bname;
private String bauthor;
public void setBname(String bname) {
this.bname = bname;
}
public void setBauthor(String bauthor) {
this.bauthor = bauthor;
}
}
在spring配置文件配置对象创建,配置属性注入
<!-- set方法注入属性 -->
<bean id="book" class="spring_learn.Book">
<!--使用property完成属性注入
name:类里面属性名称
value:向属性注入的值
-->
<property name="bname" value="西游记"></property>
<property name="bauthor" value="吴承恩"></property>
</bean>
test:
@Test
public void test(){
//1.加载spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
//2.获取配置创建的对象
Book book = context.getBean("book", Book.class);
System.out.println(book.toString());//后来在book类中加了一个tostring方法
}
第二种注入方法:有参数构造注入
public class Order {
private String oname;
private String address;
public Order(String oname, String address) {
this.oname = oname;
this.address = address;
}
}
spring配置文件:
<bean id="orders" class="spring_learn.Order">
<constructor-arg name="oname" value="烤鸭"></constructor-arg>
<constructor-arg name="address" value="china"></constructor-arg>
</bean>
xml注入其他类型属性:
1.字面量
-
null值
<property name="address"> <null></null> </property>
-
属性值包含特殊符号
<property name="address"> <value><![CDATA[<<南京>>]]></value> </property>
也可以转义。
2.注入属性-外部bean:
(1)创建两个类service和dao类:
service:
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void add(){
System.out.println("service add................");
userDao.update();
}
}
dao:
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("dao update.....");
}
}
(2)在service调用dao方法:
(3)在spring配置文件中进行配置
<bean name="userService" class="外部bean.service.UserService">
<property name="userDao" ref="userdaoImpl"></property>
</bean>
<bean name="userdaoImpl" class="外部bean.dao.UserDaoImpl"></bean>
3.注入属性-内部bean和级联赋值:
部门类
public class Dept {
private String dname;
public void setDname(String dname){
this.dname = dname;
}
public String getDname() {
return dname;
}
}
员工类:
//员工类
public class Emp {
private String ename;
private String gender;
private Dept dept;
public void setEname(String ename) {
this.ename = ename;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDept(Dept dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Emp{" +
"ename='" + ename + '\'' +
", gender='" + gender + '\'' +
", dept=" + dept.getDname() +
'}';
}
}
<bean id="emp" class="内部bean.Emp">
<property name="ename" value="lucy"></property>
<property name="gender" value="女"></property>
<property name="dept">
<bean id="dept" class="内部bean.Dept">
<property name="dname" value="销售部"></property>
</bean>
</property>
</bean>
第二种
<!-- 级联赋值 -->
<bean id="emp" class="内部bean.Emp">
<property name="ename" value="lucy"></property>
<property name="gender" value="女"></property>
<property name="dept" ref="dept"></property>
<property name="dept.dname" value="销售部"></property>
</bean>
<bean id="dept" class="内部bean.Dept">
<property name="dname" value="保安"></property>
</bean>
注意要在emp类中写dept的get方法。
4.注入集合属性
-
注入数组类型属性
-
注入List集合属性
-
主图Map集合属性
准备好类:
public class stu {
// 数组类型属性
private String[] courses;
// List集合类型属性
private List<String> list;
// map集合属性
private Map<String,String> maps;
// set集合类型属性
private Set<String> sets;
// list集合,但是值是对象
private List<Course> courseList; //course类提前写好了,只有一个属性name
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
public void setSets(Set<String> sets) {
this.sets = sets;
}
public void setCourses(String[] courses) {
this.courses = courses;
}
public void setList(List<String> list) {
this.list = list;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
@Override
public String toString() {
return "stu{" +
"courses=" + Arrays.toString(courses) +
", list=" + list +
", maps=" + maps +
", sets=" + sets +
", courseList=" + courseList +
'}';
}
}
spring配置
<bean id="stu" class="注入集合属性.stu">
<!-- 数组类型 -->
<property name="courses">
<array>
<value>java</value>
<value>数据库</value>
</array>
</property>
<property name="list">
<list>
<value>张三</value>
<value>小三</value>
</list>
</property>
<property name="maps">
<map>
<entry key="JAVA" value="java"></entry>
<entry key="PHP" value="php"></entry>
</map>
</property>
<property name="sets">
<set>
<value>Mysql</value>
<value>Redis</value>
</set>
</property>
<property name="courseList">
<list>
<ref bean="course1"></ref>
<ref bean="course2"></ref>
</list>
</property>
</bean>
<bean id="course1" class="注入集合属性.Course">
<property name="cname" value="spring5"></property>
</bean>
<bean id="course2" class="注入集合属性.Course">
<property name="cname" value="java"></property>
</bean>
把集合注入部分提取出来
(1)在spring配置文件中引入名称空间util
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
</beans>
(2)使用util标签
<!-- 1.提取list集合类型属性注入 -->
<util:list id="bookList">
<value>西游记</value>
<value>水浒传</value>
<value>西厢记</value>
</util:list>
<!-- 2.注入 -->
<bean id="book" class="注入集合属性.Book">
<property name="list" ref="bookList"></property>
</bean>
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");
Book book = context.getBean("book", Book.class);
System.out.println(book.toString());
}
(2) 基于注解方式实现
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值…)
(2)注解可以作用在类、方法、属性上
(3)简化xml配置,
Spring针对Bean管理中创建对象提供注解
-
① @Component
-
② @Service
-
③ @Controller
-
④ @Repository
*功能是一样的,都可以用来创建bean实例,在实际开发中使用习惯不一样。
1.使用步骤:
第一步 引入AOP依赖。
第二步 开启组件扫描
<?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:p="http://www.springframework.org/schema/p"
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 http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启组件扫描 -->
<context:component-scan base-package="注解"></context:component-scan>
</beans>
第三步 创建类,在类上面添加创建对象注解。
//在注解里面value属性值可以不写
//如果不写,默认值是类名称,首字母小写
@Component(value = "userService") //<bean id="userService" class=".."><bean/>
public class UserService {
public void add(){
System.out.println("add.....");
}
}
2.组件扫描配置中的常见两个方法:
<!-- 示例一:
use-default-filters="false" 表示现在不使用默认filter,自己配置filter
context:include-filter , 设置扫描哪些内容
-->
<context:component-scan base-package="注解" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 实例二
下面配置扫描包所有内容
context:exclude-filter 设置哪些内容不扫描
-->
<context:component-scan base-package="注解">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
3.基于注解方式实现属性注入
@Autowired:根据属性类型进行自动装配
@Qualifier: 根据属性名称进行注入
@Resource:可以根据类型注入,也可以根据名称注入
@Value: 注入普通类型属性
(1) 把service和dao对象创建,在service和dao类添加创建对象注解。
@Service
public class UserService {}
@Repository
public class UserDaoImpl implements UserDao{
@Override
public void add() {
System.out.println("dao add......");
}
}
(2) 在service对象中注入dao对象,在service类添加dao类型属性,在属性上面使用注解。
@Service
public class UserService {
//定义dao类型属性 添加注入属性注解
@Autowired
private UserDao userDao;
public void add(){
System.out.println("add.....");
userDao.add();
}
}
使用@Resource实例演示: 不建议使用,不是spring中的,是java的拓展包内。
import javax.annotation.Resource;
@Repository(value = "userDaoImpl1")
public class UserDaoImpl implements UserDao{}
//在service中
@Resource //根据类型注入
@Resource(name = "userDaoImpl1") //根据名称注入
private UserDao userDao;
4.完全注解开发
(1)创建配置类,替代xml配置文件
@Configuration //作为配置类
@ComponentScan(basePackages = {"注解"})
public class SpringConfig {
}
(2)test方法
@Test
public void test2(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService", UserService.class);
......
}
其余的方法都一样。
3.FactoryBean
Spring有两种类型bean,一种是普通bean,另外一种工厂bean(FactoryBean)。
普通bean:在配置文件中定义bean类型就是返回类型。
工厂bean:在配置文件中定义bean类型可以和返回类型不一样。
—1:让这个类作为工厂bean,实现接口FactoryBean
—2:实现接口里面的方法,在实现的方法中定义返回的bean类型
public class Mybean implements FactoryBean {
//定义返回bean
@Override
public Object getObject() throws Exception {
return null;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}
4.Bean的作用域
在Spring里面,设置创建bean实例是单实例还是多实例,
默认是单实例对象,就算创建了多个对象,地址是相同的。
在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例。
scope属性值: 第一个值为默认值(singleton),表示单实例对象,在加载spring配置文件时就会创建这个单实例对象;第二个值为(prototype),表示多实例对象,在调用getbean方法时创建一个新对象。
5.Bean的生命周期
生命周期:从对象创建到对象销毁的过程。
(1)通过构造器创建bean实例(无参数构造)
(2)为bean的属性设置值和对其他bean引用(调用set方法)。
(把bean实例传递给bean后置处理器的方法)
(3)调用bean的初始化的方法(需要进行配置初始化的方法)。
(把bean实例传递给bean后置处理器的方法)
(4) bean 可以使用了(对 象获取到了)。
(5)当容器关闭时候,调用bean的销毁的方法(需要进行配置销毁的方法)
6.xml自动装配
了解即可,实际开发很少用到。
自动装配:根据指定装配规则(属性名称或属性类型),spring自动将匹配的属性值注入。
实现自动装配: bean标签属性autowire,配置自动装配。
autowire属性常用两个值:byName根据属性名称注入,byType根据属性类型注入。
<bean id="emp" class="自动装配.Emp" autowire="byName">
</bean>
<bean id="dept" class="自动装配.Dept"></bean>
7.引入外部属性文件
以数据库为例:
1.直接配置数据库信息。
(1)配置druid连接池
(2)引入连接池jar包。
<!-- 直接配置连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="xxxxxxxx"></property>
</bean>
2.引入外部属性文件配置数据库连接池。
(1)创建外部属性文件,properties格式文件
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=2018zeshan!
(2)引入context名称空间
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
(3)在spring配置文件使用标签引入外部属性文件
<!-- 引入外部属性文件 -->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClass}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
2.AOP
2.1 AOP概念
面向切面编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP中的一些术语:
(1)连接点:类里面哪些方法可以被增强,这些方法称为连接点。
(2)切入点:实际被真正增强的方法,称为切入点。
(3)通知(增强):实际增强的逻辑部分称为通知。
通知有多种类型:
* 前置通知
* 后置通知
* 环绕通知
* 异常通知
* 最终通知
(4)切面:把通知应用到切入点的过程
2.2 AOP底层原理
1.AOP底层使用动态代理
(1)有两种情况动态代理
-
有接口情况
- 使用JDK动态代理
- 使用JDK动态代理
-
没有接口情况
- 使用CGLIB动态代理
- 使用CGLIB动态代理
2.3 AOP(JDK动态代理)
使用JDK动态代理,使用Proxy类里面的方法创建代理对象。
(1)调用newProxyInstance方法:
共有三个参数:
第一个参数为类加载器;
第二个参数为增强方法所在的类,这个类实现的接口;
第三个参数为实现这个接口InvocationHandler,创建代理对象,写增强的方法。
(2)代码示例:
新建接口
public interface UserDao {
public int add(int a,int b);
public String update(String id);
}
创建接口实现类,实现方法
public class UserDaoImpl implements UserDao{
@Override
public int add(int a, int b) {
return a+b;
}
@Override
public String update(String id) {
return id;
}
}
使用Proxy类
public class JDKProxy {
public static void main(String[] args) {
Class[] interfaces = {UserDao.class};
//创建实现类的代理对象第一种方法
// Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// return null;
// }
// })
UserDaoImpl userDao = new UserDaoImpl();
// 接口 = 实现类的代理对象
UserDao dao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
int result = dao.add(1,2);
System.out.println(result);
}
}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler{
//1 把创建的是谁的代理对象,把谁传进来
//有参数构造
private Object object;
public UserDaoProxy(Object object){
this.object = object;
}
//写增强的逻辑
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法之前
System.out.println("方法之前执行......"+method.getName()+":传递的参数为。。。"+ Arrays.toString(args));
//被增强的方法执行
Object res = method.invoke(object, args);
//方法之后
System.out.println("方法之后执行......" + object);
return res;
}
}
2.4 AOP操作
准备工作:
Spring框架一般都是基于AspectJ实现AOP操作,AspectJ独立AOP框架。
一般把AspectJ和Spring框架一起使用,进行AOP相关操作。
切入点表达式:
作用:知道对哪个类里面的哪个方法进行增强。
语法结构:
execution( 【权限修饰符】【返回类型】【类全路径】【方法名称】(【参数列表】))
举例1:对 com.aop.dao.BookDao 类里面的add进行增强:
execution(* com.aop.dao.BookDao.add(…))
举例2:对 com.aop.dao.BookDao 类里面的所有方法进行增强:
execution(* com.aop.dao.BookDao.*(…))
举例3:对 com.aop.dao 所有类里面的所有方法进行增强:
execution(* com.aop.dao. * . *(…))
基于AspectJ实现AOP操作:
(1)基于xml配置文件
(2)基于注解方式(*)
1.创建类,在类里面创建方法。
public class User {
public void add(){
System.out.println("add....");
}
}
2.创建增强类,编写增强的逻辑。
(1)在增强类里面,创建方法,让不同方法代表不同通知类型。
3.进行通知的配置
(1)在spring配置文件中,开启注解扫描。
<?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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="AOP.注解方式"></context:component-scan>
</beans>
(2)使用注解创建User和UserProxy对象。
(3)在增强类上面添加注解 @Aspect
(4)在spring配置文件中开启生成代理对象
<!-- 开启Aspect生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
4.配置不同类型的通知
在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置。
//增强的类
@Component
@Aspect //生成代理对象
public class UserProxy {
//前置通知
@Before(value = "execution(* AOP.注解方式.User.add(..))")
public void bfore(){
System.out.println("before....");
}
}
其他通知使用:
//增强的类
@Component
@Aspect //生成代理对象
public class UserProxy {
//相同切入点抽取
@Pointcut(value = "execution(* AOP.注解方式.User.add(..))")
public void point(){}
//前置通知
@Before(value = "point()")
public void bfore(){
System.out.println("before....");
}
//最终通知
@After(value = "point()")
public void after(){
System.out.println("After....");
}
//后置通知(返回通知)
@AfterReturning(value = "point()")
public void afterReturning(){
System.out.println("afterReturning....");
}
//异常通知
@AfterThrowing(value = "point()")
public void afterThrowing(){
System.out.println("afterThrowing....");
}
//环绕通知
@Around(value = "point()")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕之前....");
proceedingJoinPoint.proceed();
System.out.println("环绕之后....");
}
}
3.JDBC-Template
Spring框架对JDBC进行封装,使用JDBC-Template方便实现对数据库操作。
步骤:
(1)引入相关jar包:mysql和druid,spring-jdbc,spring-tx,spring-orm。
(2)在spring配置文件中配置数据库连接池。
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="2018zeshan!"></property>
</bean>
(3)配置JDBC-Template对象,注入 DataSource。
<!-- JDBCTemplate对象 -->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入datasource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
开启注解的组件扫描:
<!-- 开启组件扫描 -->
<context:component-scan base-package="JDBC"></context:component-scan>
(4)创建Service类,创建Dao类,在dao注入JdbcTemplate对象。
(5)对应数据库的表创建实体类。
public class Book {
private String book_id;
private String book_name;
private String ustatus;
public String getBook_id() {
return book_id;
}
public void setBook_id(String book_id) {
this.book_id = book_id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getUstatus() {
return ustatus;
}
public void setUstatus(String ustatus) {
this.ustatus = ustatus;
}
}
(6)编写service和dao
在dao进行数据库添加操作:
增加操作
调用JdbcTemplate对象里面的update方法实现添加操作。
@Repository
public class BookDaoImpl implements BookDao{
//注入jdbc
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void add(Book book) {
String sql = "insert into t_book values(?,?,?)";
int update = jdbcTemplate.update(sql, book.getBook_id(), book.getBook_name(), book.getUstatus());
System.out.println(update);
}
}
测试类:
public class Test {
@org.junit.Test
public void testJdbc(){
ApplicationContext context =
new ClassPathXmlApplicationContext("JDBC/druid.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();
book.setBook_id("1");
book.setBook_name("java");
book.setUstatus("a");
bookService.addBook(book);
}
}
修改和删除
BookDaoImpl:
@Override
public void update(Book book) {
String sql = "update t_book set book_name=?,ustatus=? where book_id=?";
Object[] args = {book.getBook_name(),book.getUstatus(),book.getBook_id()};
int update = jdbcTemplate.update(sql, args);
System.out.println(update);
}
@Override
public void delete(String id) {
String sql = "delete from t_book where book_id=?";
int update = jdbcTemplate.update(sql, id);
System.out.println(update);
}
bookService:
//修改
public void updateBook(Book book){
bookDao.update(book);
}
//删除
public void deleteBook(String id){
bookDao.delete(id);
}
查询
返回某个值
BookDaoImpl:
@Override
public int selectCount() {
String sql = "select count(*) from t_book";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
test:
@org.junit.Test //返回某个值
public void testJdbc3(){
ApplicationContext context =
new ClassPathXmlApplicationContext("JDBC/druid.xml");
BookService bookService = context.getBean("bookService", BookService.class);
int i = bookService.fingCount();
System.out.println(i);
}
返回对象
BookDaoImpl:
@Override
public Book findBookInfo(String id) {
String sql = "select * from t_book where book_id=?";
//RowMapper是一个接口,返回不同类型数据,使用这个接口完成数据封装。
Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
return book;
}
bookService:
//查询返回对象
public Book findOne(String id){
return bookDao.findBookInfo(id);
}
test
@org.junit.Test //返回对象
public void testJdbc4(){
ApplicationContext context =
new ClassPathXmlApplicationContext("JDBC/druid.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book one = bookService.findOne("1");
System.out.println(one);
}
返回集合值
BookDaoImpl:
@Override
public List<Book> findAll() {
String sql = "select * from t_book";
List<Book> books = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
return books;
}
bookService:
//查询返回集合
public List<Book> findAll(){
return bookDao.findAll();
}
test
@org.junit.Test //返回集合
public void testJdbc5(){
ApplicationContext context =
new ClassPathXmlApplicationContext("JDBC/druid.xml");
BookService bookService = context.getBean("bookService", BookService.class);
List<Book> all = bookService.findAll();
System.out.println(all);
}
批量操作:
增加:
BookDaoImpl:
@Override //批量增加
public void batchAddBook(List<Object[]> batchArgs) {
String sql = "insert into t_book values(?,?,?)";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
bookService:
//批量添加
public void batchAdd(List<Object[]> batchArgs){
bookDao.batchAddBook(batchArgs);
}
test
@org.junit.Test //批量添加
public void testJdbc6(){
ApplicationContext context =
new ClassPathXmlApplicationContext("JDBC/druid.xml");
BookService bookService = context.getBean("bookService", BookService.class);
ArrayList<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3","C++","a"};
Object[] o2 = {"4","JS","a"};
Object[] o3 = {"5","C#","a"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
bookService.batchAdd(batchArgs);
}
4.事务操作
1.事务管理介绍:
1.事务添加到JavaEE三层结构里面的Service层(业务逻辑层)。
如果业务逻辑层出现有一方错误,代码实现同步不了,会出现一方成功一方失败的现象所以要使用到事务的架构(需要使用try catch结构,且前三步在try中执行)
2.在spring进行事务管理操作。
两种方式:編程式事务管理和声明式事务管理。
3.声明式事务管理:
(1)基于注解方式
1.在spring配置文件中配置事务管理器:
<!-- 创建事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
2.在spring配置文件中,开启事务注解。
引入命名空间 tx
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.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">
开启事务注解:
<!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
3.在service类上面(获取service类里面) 添加事务注解
@Transactional
可以添加到类上面也可以添加到方法上面,
如果添加到类上面,这个类里所有的方法都有事务;
如果添加到方法上面,这个方法被添加了事务。
(2)基于xml配置文件方式
4.在spring进行声明式事务管理,底层使用AOP原理。
5.Spring事务管理API
(1)提供了一个接口,代表事务管理器,这个接口针对不同框架提供不同的实现类。
2.声明式事务管理参数配置
在service类上面添加注解@Transactional,在这个注解里可以配置事务相关参数。
-
propagation:事务传播行为
(1)多事务方法直接进行调用,这个过程中事务是如何进行管理的。
示例:
@Service @Transactional(propagation = Propagation.REQUIRED) public class UserService {}
-
isolation:事务隔离级别
多事务之间操作如果有隔离不会发生什么事情
但没有隔离会发生以下三种情况:脏读、不可重复读、虚(幻)读脏读:一个未提交事务读取到另一个未提交事务的数据(事件回滚,导致A读取B还未提交的事务,应该读取原始数据)
不可重复读:一个未提交的事务,获取到了一个已经提交修改的事务(A读取B提交的事务,正常来说都提交了才能读取)
幻读:一个未提交的数据获取到了另一个事务添加数据
为了防止以上情况,设置事务的隔离性
事务情况 | 脏读 | 不可重复读 | 幻读 |
---|---|---|---|
READ UNCOMMITTED(读未提交) | 有 | 有 | 有 |
READ COMMITTED (读已提交) | 无 | 有 | 有 |
REPEATABLE READ(可重复读) | 无 | 无 | 有 |
SERIALIZABLE(串行化) | 无 | 无 | 无 |
-
timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是 -1 ,设置时间以秒单位进行计算 -
readOnly:是否只读
(1)读:查询操作,写:添加修改删除操作
(2)readOnly 默认值 false,表示可以查询,可以添加修改删除操作
(3)设置 readOnly 值是 true,设置成 true 之后,只能查询 -
rollbackFor:回滚
设置出现哪些异常进行事务回滚
-
noRollbackFor:不会滚
设置出现哪些异常不进行事务回滚
3.完全注解声明式事务管理
使用配置类替换xml
package bank.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration //配置类
@ComponentScan(basePackages = "bank") //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
//创建数据库lianjiechi
@Bean
public DruidDataSource getDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("2018zeshan!");
return dataSource;
}
//创建jdbcTemplate对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入datasource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
@Bean
//创建事务管理器
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
测试:
@Test
public void test2(){
ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
UserService service = context.getBean("userService",UserService.class);
service.accountMoney();
}
rceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration //配置类
@ComponentScan(basePackages = “bank”) //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
//创建数据库lianjiechi
@Bean
public DruidDataSource getDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(“com.mysql.jdbc.Driver”);
dataSource.setUrl(“jdbc:mysql://localhost:3306/test”);
dataSource.setUsername(“root”);
dataSource.setPassword(“2018zeshan!”);
return dataSource;
}
//创建jdbcTemplate对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入datasource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
@Bean
//创建事务管理器
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
测试:
```java
@Test
public void test2(){
ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
UserService service = context.getBean("userService",UserService.class);
service.accountMoney();
}