目录
16.基于aspectj注解aop
1 : 使用注解的方式实现AOP操作
第一步 :创建对象
在增强类上面使用注解完成AOP操作.
1 . 在增强类上面使用@Aspect注解
2 . 在要增强的方法上面使用不同的注解
public class User {
public void show() {
System.out.println("我是User类的show()方法");
}
public void add() {
System.out.println("我是User类的add()方法.....");
}
public void delete() {
System.out.println("我是User类的delete()方法");
}
public void update() {
// System.out.println(1/0);
System.out.println("我是User类的update()方法,用于测试异常增强");
}
public void find() {
System.out.println("我是User类的find()方法");
}
}
@Aspect
public class MyUser {
/**
* 给User类的shou()方法进行前置增强
*/
@Before("execution(* com.edu.xiaoniu.bean.User.show(..))")
public void before() {
System.out.println("前置增强");
}
/**
* 给User类的add()方法进行后置增强
*/
@AfterReturning("execution(* com.edu.xiaoniu.bean.User.add(..))")
public void after() {
System.out.println("后置增强");
}
/**
* 给User类的delete()方法进行环绕增强
*
* @param proceedingJoinPoint
* @throws Throwable
*/
@Around("execution(* com.edu.xiaoniu.bean.User.delete(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕增强---之前");
proceedingJoinPoint.proceed();
System.out.println("环绕增强---之后");
}
/**
* 给User类的update方法进行异常增强
*/
@AfterThrowing("execution(* com.edu.xiaoniu.bean.User.update(..))")
public void error() {
System.out.println("我是异常增强");
}
/**
* 给User类的find()方法进行最终增强
*/
@After("execution(* com.edu.xiaoniu.bean.User.find(..))")
public void finallyAdd() {
System.out.println("我是最终增强");
}
}
/**
* 给User类的shou()方法进行前置增强
*/
@Before("execution(* com.edu.xiaoniu.bean.User.show(..))")
public void before() {
System.out.println("前置增强");
}
/**
* 给User类的add()方法进行后置增强
*/
@AfterReturning("execution(* com.edu.xiaoniu.bean.User.add(..))")
public void after() {
System.out.println("后置增强");
}
/**
* 给User类的delete()方法进行环绕增强
*
* @param proceedingJoinPoint
* @throws Throwable
*/
@Around("execution(* com.edu.xiaoniu.bean.User.delete(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕增强---之前");
proceedingJoinPoint.proceed();
System.out.println("环绕增强---之后");
}
/**
* 给User类的update方法进行异常增强
*/
@AfterThrowing("execution(* com.edu.xiaoniu.bean.User.update(..))")
public void error() {
System.out.println("我是异常增强");
}
/**
* 给User类的find()方法进行最终增强
*/
@After("execution(* com.edu.xiaoniu.bean.User.find(..))")
public void finallyAdd() {
System.out.println("我是最终增强");
}
}
第二步 :通过xml配置文件的方式,创建User类和MyUser类
引入约束,并且开启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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启Aop自动代理 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- 创建对象 -->
<bean id="user" class="com.edu.xiaoniu.bean.User"></bean>
<bean id="myUser" class="com.edu.xiaoniu.bean.MyUser"></bean>
</beans>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- 创建对象 -->
<bean id="user" class="com.edu.xiaoniu.bean.User"></bean>
<bean id="myUser" class="com.edu.xiaoniu.bean.MyUser"></bean>
</beans>
第三步 : 编写测试方法测试
public class TestUser {
/**
* 测试show()方法的前置增强
*/
@Test
public void testBefore() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user",User.class);
user.show();
}
/**
* 测试add方法的后置增强
*/
@Test
public void testAfter() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user",User.class);
user.add();
}
/**
* 测试delete方法的环绕增强
*/
@Test
public void testAround() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user",User.class);
user.delete();
}
/**
* 测试update类的异常增强
*/
@Test
public void testerror() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user",User.class);
user.update();
}
/**
* 测试delete()方法的最终增强
*/
@Test
public void testfinallyAdd() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user",User.class);
user.find();
}
}
17 . Spring的jdbcTemplate操作
1 jdbcTemplate介绍:
(1)spring框架是一站式框架,针对javaee三层,在每一层都提供解决技术,在dao层提供技术是jdbcTemplate
(2)之前在web阶段学习过dbutils,现在使用jdbcTemplate类似于dbutils,使用jdbcTemplate实现对数据库crud操作
(3)jdbcTemplate对jdbc进行封装,减少代码编写
2 准备工作
(1)导入新的jar包
spring-jdbc-4.2.4.RELEASE.jar
spring-tx-4.2.4.RELEASE.jar
(2)数据库驱动jar包
mysql-connector-java-5.0.4-bin.jar
3 操作步骤
(1)设置数据库相关的信息
(2)创建jdbcTemplate对象,传递数据库信息
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_day03");
dataSource.setUsername("root");
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
(3)调用jdbcTemplate对象里面的方法实现crud操作
String sql = "insert into t_user values(?,?,?)";
int rows = jdbcTemplate.update(sql,5,"张sss","美国");
System.out.println(rows);
4 测试代码
1.添加数据
/**
* 添加操作
* @throws Exception
*/
@Test
public void testAdd() throws Exception {
//(1)设置数据库相关的信息
//spring框架内置连接池
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_day03");
dataSource.setUsername("root");
dataSource.setPassword("123456");
//(2)创建jdbcTemplate对象,传递数据库信息
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//(3)调用jdbcTemplate对象里面的方法实现添加操作
String sql = "insert into t_user values(?,?,?)";
int rows = jdbcTemplate.update(sql,5,"张sss","美国");
System.out.println(rows);
}
2.删除数据
/**
* 删除数据
*/
@Test
public void testDelete() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_day03");
dataSource.setUsername("root");
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "delete from t_user where id=?";
int i = jdbcTemplate.update(sql, 1);
System.out.println(i);
}
3.修改数据
/**
* 修改操作
*/
@Test
public void testUpdate() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_day03");
dataSource.setUsername("root");
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "update t_user set address=? where id=?";
int rows = jdbcTemplate.update(sql,"USA",2);
System.out.println(rows);
}
4.查询数据条数
/**
* 查询t_user表中数据的条数
*/
@Test
public void testCount() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_day03");
dataSource.setUsername("root");
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "select count(*) from t_user";
//调用模板的方法实现查询返回某个值
int count = jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println(count);
}
自己写类,实现rowMapper接口,自己封装数据
class MyRowMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int rows) throws SQLException {
//1 从结果集把数据获取出来
int id = rs.getInt("id");
String username = rs.getString("username");
String address = rs.getString("address");
//2 把获取数据封装对象里面
User user = new User();
user.setId(id);
user.setUsername(username);
user.setAddress(address);
//3 封装对象返回
return user;
}
}
创建一个user对象
public class User {
private int id;
private String username;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", address=" + address + "]";
}
}
5.查询所有数据(返回对象)
/**
* 查询返回一个对象
*/
@Test
public void testObject() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_day03");
dataSource.setUsername("root");
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "select * from t_user where id=?";
//调用JdbcTemplate方法实现操作
User user = jdbcTemplate.queryForObject(sql,new MyRowMapper(), 3);
System.out.println(user);
}
6.查询所有数据(返回集合)
/**
* 查询所有对象,返回list集合
*/
@Test
public void testList() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_day03");
dataSource.setUsername("root");
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "select * from t_user";
//查询返回list集合。调用jdbcTemplate的方法
List<User> list = jdbcTemplate.query(sql, new MyRowMapper());
System.out.println(list);
}
18 . Spring配置连接池
1.Spring配置内置连接池
1.1XML配置文件
<?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"
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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- spring框架内置数据库连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///spring_day03"></property>
<property name="username" value="root"></property>
<property name="password" value="123465"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
1.2测试方法
/**
* 添加操作
* @throws Exception
*/
@Test
public void testAdd() throws Exception {
//通过加载xml配置文件 创建内部连接池 DriverManagerDataSource对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DriverManagerDataSource dataSource = context.getBean("dataSource", DriverManagerDataSource.class);
//通过配置文件创建JdbcTemplate对象
JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate",JdbcTemplate.class);
//(3)调用jdbcTemplate对象里面的方法实现添加操作
String sql = "insert into t_user values(?,?,?)";
int rows = jdbcTemplate.update(sql,5,"张sss","美国");
System.out.println(rows);
}
2 . Spring配置c3p0连接池
2.1 导入jar包
c3p0-0.9.1.2.jar
2.2 配置XML文件
<!-- c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
2.3 测试方法
/**
* 添加操作
* @throws Exception
*/
@Test
public void testAdd() throws Exception {
//c3p0连接池
// ComboPooledDataSource dataSource = new ComboPooledDataSource();
// dataSource.setDriverClass("com.mysql.jdbc.Driver");
// dataSource.setJdbcUrl("jdbc:mysql:///spring_day03");
// dataSource.setUser("root");
// dataSource.setPassword("123456");
//通过加载xml配置文件 c3p0连接池 创建ComboPooledDataSource对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ComboPooledDataSource dataSource = context.getBean("dataSource", ComboPooledDataSource.class);
//(2)创建jdbcTemplate对象,传递数据库信息
//JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//通过配置文件创建JdbcTemplate对象
JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate",JdbcTemplate.class);
//(3)调用jdbcTemplate对象里面的方法实现添加操作
String sql = "insert into t_user values(?,?,?)";
int rows = jdbcTemplate.update(sql,5,"张sss","美国");
System.out.println(rows);
}
19 . 引入外部配置文件
1 . 在src下面创建jdbc属性文件,文件类型为properties
2 . 引入配置文件,引入外部配置文件有俩种方式
方式一:
<!-- 引入外部配置文件的第一种方式 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:db.properties"></property>
</bean>
方式二:
<!-- 引入外部配置文件的第二种方式 -->
<!-- <context:property-placeholder location="classpath:db.properties"/> -->
具体配置连接池时的使用方式,以c3p0为例:
<?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"
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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 引入外部配置文件的第一种方式 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:db.properties"></property>
</bean>
<!-- 引入外部配置文件的第二种方式 -->
<!-- <context:property-placeholder location="classpath:db.properties"/> -->
<!-- c3p0连接池 -->
<!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
20 . Dao使用jdbcTemplate
1 : 在web项目中,提交表单到action里面,在action调用service,service调用dao
(1)在dao里面使用jdbcTemplate做操作
1.1创建User对象,设置id,username,address三个属性,并且生成get和set方法
public class User {
private int id;
private String username;
private String address;
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", address=" + address + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2 : 创建service和dao类,在service注入dao对象
2.1 创建UserDao类
public class UserDao {
}
2.2 创建UserServic对象,注入UserDao对象
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
3 : 使用配置文件创建jdbcTemplate对象,在jdbcTemplate对象里面注入DataSource
(1)使用set方法注入
<?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"
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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 使用c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 引入外部文件的第二种方式 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="userDao" class="com.edu.xiaoniu.dao.UserDao"></bean>
<bean id="userService" class="com.edu.xiaoniu.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
4 : 关系注入的描述
(1)在service里面注入dao对象
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
/**
* 调用userDao的添加方法
* @return
*/
public int addUser() {
int rows = userDao.addUser();
return rows;
}
/**
* 调永userDao的删除方法
* @param id
* @return
*/
public int delUser(int id) {
return userDao.delUser(id);
}
/**
* 调用userDao的更新方法
* @param address
* @param id
* @return
*/
public int updateUserById(String address, int id) {
return userDao.updateUserById(address, id);
}
/**
* 调用userDao的更新方法
* @param address
* @param id
* @return
*/
public User findUserById(int id) {
return userDao.findUserById(id);
}
/**
* 调用userDao的更新方法
* @param address
* @param id
* @return
*/
public List<User> findUserAll() {
return userDao.findUserAll();
}
}
(2)在dao里面注入jdbcTemplate对象
public class UserDao {
/**
* 添加
* @return
*/
public int addUser() {
//操作数据,添加操作
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate template = context.getBean("jdbcTemplate", JdbcTemplate.class);
String sql = "insert into t_user values(?,?,?)";
int rows = template.update(sql, 10,"赵丽颖","河北");
return rows;
}
/**
* 根据ID删除一条数据
* @return
*/
public int delUser(int id) {
//操作数据,添加操作
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate template = context.getBean("jdbcTemplate", JdbcTemplate.class);
String sql = "delete from t_user where id = ?";
int rows = template.update(sql, id);
return rows;
}
/**
* 根据ID更新一条数据
* @return
*/
public int updateUserById(String address, int id) {
//操作数据,添加操作
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate template = context.getBean("jdbcTemplate", JdbcTemplate.class);
String sql = "update t_user set address = ? where id = ?";
int rows = template.update(sql, address,id);
return rows;
}
/**
* 根据ID查询一条数据,返回对象
* @return
*/
public User findUserById(int id) {
//操作数据,添加操作
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate template = context.getBean("jdbcTemplate", JdbcTemplate.class);
String sql = "select * from t_user where id = ?";
return template.queryForObject(sql,new MyRowMapper(),id);
}
/**
* 查询所有数据,返回集合
* @return
*/
public List<User> findUserAll() {
//操作数据,添加操作
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate template = context.getBean("jdbcTemplate", JdbcTemplate.class);
String sql = "select * from t_user";
return template.query(sql,new MyRowMapper());
}
}
MyRowMapper类
public class MyRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rows) throws SQLException {
int id = rs.getInt("id");
String username = rs.getString("username");
String address = rs.getString("address");
User user = new User();
user.setId(id);
user.setUsername(username);
user.setAddress(address);
return user;
}
}
(3)在jdbcTemplate里面注入DataSource
<!-- 使用c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
(4)测试方法
public class TestJdbc {
/**
* 测试添加
*/
@Test
public void testtmAdd() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService",UserService.class);
int rows = userService.addUser();
if (rows >= 1) {
System.out.println("恭喜,恭喜,添加成功");
}
}
/**
* 测试删除
*/
@Test
public void testtmdelById() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService",UserService.class);
int rows = userService.delUser(3);
if (rows >= 1) {
System.out.println("非常遗憾的告诉您,您被淘汰了,下次继续努力");
}
}
/**
* 测试修改
*/
@Test
public void testtmupdateUserById() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService",UserService.class);
int rows = userService.updateUserById("中国", 1);
if (rows >= 1) {
System.out.println("非常遗憾的告诉您,您遣返了,请带好自首的证据");
}
}
/**
* 测试根据ID查询,返回对象
*/
@Test
public void testtmFindUserById() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService",UserService.class);
User user = userService.findUserById(6);
System.out.println(user);
}
/**
* 测试查询所有的数据,返回集合
*/
@Test
public void testtmFindUserAll() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService",UserService.class);
List<User> list = userService.findUserAll();
System.out.println(list);
}
}
21 . Spring的事物管理
以银行转账为例
创建UserDao类,实现余额的增减功能
public class UserDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 转出金额
* @return
*/
public void outMoney() {
//操作数据,添加操作
String sql = "UPDATE t_bank_info SET money = money - 100 WHERE id =?";
jdbcTemplate.update(sql, 1);
}
/**
* 转入金额
* @return
*/
public void makeMoney() {
//操作数据,添加操作
String sql = "UPDATE t_bank_info SET money = money + 100 WHERE id =?";
jdbcTemplate.update(sql, 2);
}
}
创建UserService类,调用UserDao里面的方法,实现金额的转入转出
@Transactional
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void transMoney() {
userDao.outMoney();
//System.out.println(1/0);
userDao.makeMoney();
}
}
声明式事物(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:aop="http://www.springframework.org/schema/aop"
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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 引入外部配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 内置的连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入DataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 通过配置文件的方式创建UserDao对象和UserService对象,将UserDao注入UserService -->
<bean id="userDao" class="com.edu.xiaoniu.dao.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="userService" class="com.edu.xiaoniu.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
<!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</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"
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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 引入外部配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 内置的连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入DataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 通过配置文件的方式创建UserDao对象和UserService对象,将UserDao注入UserService -->
<bean id="userDao" class="com.edu.xiaoniu.dao.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="userService" class="com.edu.xiaoniu.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
<!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
测试方法
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.edu.xiaoniu.service.UserService;
public class TestJdbc {
@Test
public void testTrandMoney() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.transMoney();
}
}