一.环境搭建及前期准备
数据库及环境依然采用上一篇博客的所有,将上篇博客中的xml配置文件删除,并改造为纯注解开发。
1.创建必要的类及配置文件,完成后项目的结构如下图
①:jdbcConfig.properties中代码如下:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
②:SpringConfiguration.java中的代码如下:
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author Roy
* @date 2020/7/29 13:55
* spring的配置类
*/
@Configuration
@ComponentScan("com.lut")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement
public class SpringConfiguration {
}
③:JdbcConfig.java中的代码如下:
package config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
/**
* @author Roy
* @date 2020/7/29 13:53
* 数据库连接的配置类
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//创建jdbcTemplate对象
@Bean(name="jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
//创建数据源对象
@Bean(name = "dataSource")
public DataSource createDataSource(){
DriverManagerDataSource ds=new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
④:TransactionConfig.java中的代码如下:
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* @author Roy
* @date 2020/7/29 13:58
* 和事务相关的配置类
*/
public class TransactionConfig {
@Bean(name="transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
⑤:修改StudentDaoImpl.java中的代码如下:
package com.lut.dao.impl;
import com.lut.dao.IStudentDao;
import com.lut.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("studentDao")
public class StudentDaoImpl implements IStudentDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public Student findStudentByName(String studentName) {
List<Student> students=jdbcTemplate.query("select * from student where name=?"
,new BeanPropertyRowMapper<Student>(Student.class),studentName);
if(students.isEmpty()){
return null;
}
if(students.size()>1){
throw new RuntimeException("结果不唯一请检查查询名称是否合法!");
}
return students.get(0);
}
public Student findStudentById(Integer studentId) {
List<Student> students=jdbcTemplate.query("select * from student where id=?",
new BeanPropertyRowMapper<Student>(Student.class),studentId);
return students.isEmpty()?null:students.get(0);
}
public void updateStudent(Student student) {
jdbcTemplate.update("update student set name=?,major=?,bookNum=? where id=?",
student.getName(),student.getMajor(),student.getBookNum(),student.getId());
}
}
⑥:修改StudentServiceImpl.java中的代码如下:
package com.lut.service.impl;
import com.lut.dao.IStudentDao;
import com.lut.domain.Student;
import com.lut.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Roy
* @date 2020/7/29 11:30
*/
@Service("studentService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读型事务的配置
public class StudentServiceImpl implements IStudentService {
@Autowired
private IStudentDao studentDao;
public Student findStudentByName(String studentName) {
return studentDao.findStudentByName(studentName);
}
public Student findStudentById(Integer studentId) {
return studentDao.findStudentById(studentId);
}
public void updateStudent(Student student) {
studentDao.updateStudent(student);
}
//需要的是读写型事务配置
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public void borrowBook(String targetName, String sourceName, int bookNum) {
//根据姓名查询被借书学生
Student source=studentDao.findStudentByName(sourceName);
//根据姓名查询借书学生
Student target=studentDao.findStudentByName(targetName);
//被借书学生bookNum减书
source.setBookNum(source.getBookNum()-bookNum);
//借书学生bookNum加书
target.setBookNum((target.getBookNum()+bookNum));
//更新被借书学生信息
studentDao.updateStudent(source);
//更新借书学生信息
studentDao.updateStudent(target);
}
}
2.创建的测试类StudentTest.java中的代码如下:
package com.lut.test;
import com.lut.service.IStudentService;
import config.SpringConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class StudentTest {
@Autowired
private IStudentService studentService;
@Test
public void testBorrow(){
studentService.borrowBook("test","d",3);
}
}
至此纯注解开发的示例就成功完成了。