Spring boot整合事务和连接池
目标:配置spring boot自带的hikari连接池,事务配置。
首先在pom.xml文件中添加依赖:
//启动器依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
//mysql驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
编写对应业务类:
package com.dsr.service;
import com.dsr.dao.Admin;
import com.dsr.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//业务类注解
@Service
public class AdminService {
public Admin queryById(int id){
return adminMapper.selectByPrimaryKey(id);
}
//事务配置注解 该业务用到多个数据库的表 如果有错 则会回滚
@Transactional
public void saveAdmin(Admin admin){
System.out.println("新增用户");
//选择性新增 属性为空则不会出现
adminMapper.insertSelective(admin);
}
}
配置文件中进行datasource配置:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3366/exam?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password: 123456
在controller类中注入datasource测试:
package com.dsr.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
@RestController
public class HellorController {
@Autowired
private DataSource dataSource;
@GetMapping("hello")
public String hello(){
System.out.println("DataSource="+dataSource);
return "hello spring boot";
}
}
打断点后可以看到:
druid连接池依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>