一.连接数据库
1.在pom.xml中添加AOP依赖
<!--spring对jdbc支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql驱动,如果其他数据库引入其他数据库驱动-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
2.application.properties配置文件中设置数据库连接信息
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=postgres
3.通过Datasource获取Connect
public static void main(String[] args) throws SQLException {
ConfigurableApplicationContext ioc = SpringApplication.run(DatabaseApplication.class, args);
DataSource dataSource = ioc.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
}
二.DataSource
1.DataSource是一个接口,它提供一种标准方式获取数据库Connect(可以灵活替换实现)
2.DataSource对象通过配置信息创建,并由SpringBoot自动创建并管理
3.DataSourceProperties读取配置,DataSourceConfiguration::Hikari创建DataSource
4.Spring默认使用HikariDataSource实现,因为它是连接池实现效率高
连接池是一种连接管理技术。通过重复利用连接,减少连接创建和关闭的开销,提高效率。
三.操作数据库
通过类JdbcTemplate操作
1.JdbcTemplate insert操作
JdbcTemplate jdbcTemplate= ioc.getBean(JdbcTemplate.class);
jdbcTemplate.update("insert into t_user(id, username) values(?, ?)", 2, "王五");
2.JdbcTemplate update操作
JdbcTemplate jdbcTemplate= ioc.getBean(JdbcTemplate.class);
jdbcTemplate.update("update t_user set username = ? where id = ?", "王五2", 2);
3.JdbcTemplate delete操作
JdbcTemplate jdbcTemplate= ioc.getBean(JdbcTemplate.class);
jdbcTemplate.update("delete from t_user where id = ?", 1);
4.JdbcTemplate select操作(一行)
JdbcTemplate jdbcTemplate= ioc.getBean(JdbcTemplate.class);
String sql= "select * from t_user where id = ?";
User user= jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 2);
5.JdbcTemplate select操作(多行)
JdbcTemplate jdbcTemplate= ioc.getBean(JdbcTemplate.class);
String sql= "select * from t_user";
List<User> users= jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
四.事务传播行为
1.概念
事务传播行为指的是当一个事务方法调用另一个事务方法,这个事务如何传递
2.类型
其中REQUIED和REQUIRES_NEW最常使用
调用者事务为外部事务,被调用者事务为内部事务(调用关系)
实现局部回滚,必须NESTED行为+ 异常方法try catch捕获
五.事务属性
1.readOnly属性
readOnly不是所有数据库都支持
通常不设置
设置该属性后不能执行数据修改操作
通知数据库,事务的全部操作都是只读的,数据库会做相应优化
优不优化取决于数据库实现(设置了也不会提高性能)
2.timeout属性
指定事务最长等待时间(秒)
事务访问数据时,可能访问被加锁数据,那么此时事务就必须等待,设置合理等待时间提高用户体验
没设置使用数据库默认等待时间
3.异常属性
当事务出现哪些异常就进行回滚或提交
设置哪些异常不回滚(noRollbackFor)
设置哪些异常回滚(rollbackFor)
默认对于RuntimeException及其子类进行回滚,非RuntimeException不会回滚
六.事务原理及失效原因
1.原理
事务->AOP->动态代理
2.失效原因
1.保证事务类是一个ioc管理的bean(AOP生效前提)
2.事务方法不能是private(cglib动态代理生效前提)
3.事务方法自己捕获异常,没有抛出(AOP无法捕获异常)
4.使用目标对象(this)调用事务方法(AOP要生效一定要通过代理对象调用)