1 概述
SpringBoot
封裝的JdbcTemplate
,使用模板模式,去除JDBC
繁瑣的重複代碼,並提供了基於註解的事務管理;下面詳細介紹如何使用JdbcTemplate
操作數據和事務管理。
2 添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
SpringBoot
會自動初始化JdbcTemplate
3 數據源配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/springboot
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
以上就是需要新增的配置,是不是非常簡單
4 業務代碼,實現數據庫增刪改查
4.1 新建數據庫,新建表
數據庫:SpringBoot
表:
CREATE TABLE `t_user` (
`user_id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR ( 255 ) NOT NULL,
`password` VARCHAR ( 255 ) NOT NULL,
`phone` VARCHAR ( 20 ) NOT NULL,
PRIMARY KEY ( `user_id` )
) ENGINE = INNODB AUTO_INCREMENT = 1018 DEFAULT CHARSET = utf8;
4.2 新建實體
@Data
@Builder
public class User {
private Integer userId;
private String userName;
private String password;
private String phone;
}
4.3 增刪改查
public interface UserService {
/**
* 新增一個用戶
*/
Integer create(User user);
/**
* 根據Name刪除一個用戶
*/
void deleteByName(String userName);
/**
* 獲取用戶總量
*/
Integer getAllUsers();
/**
* 刪除所有用戶
*/
void deleteAllUsers();
/**
* 先清空數據
* 再新增數據
* 要求再一個事物中執行
*/
void clearAdd(User user);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer create(User user) {
return jdbcTemplate.update("insert into T_USER(USER_NAME, PASSWORD, PHONE) values (?, ?, ?)",
user.getUserName(), user.getPassword(), user.getPhone());
}
@Override
public void deleteByName(String userName) {
jdbcTemplate.update("delete from T_USER where USER_Name = ?", userName);
}
@Override
public Integer getAllUsers() {
return jdbcTemplate.queryForObject("select count(1) from T_USER", Integer.class);
}
@Override
public void deleteAllUsers() {
jdbcTemplate.update("delete from T_USER");
}
@Transactional
@Override
public void clearAdd(User user) {
this.deleteAllUsers();
this.create(user);
}
}
當引入jdbc
依賴之後,SpringBoot
會自動默認分別注入DataSourceTransactionManager
或JpaTransactionManager
,所以我們不需要任何額外配置就可以用@Transactional
註解進行事務的使用。spring-boot-starter-jdbc
會觸發DataSourceTransactionManagerAutoConfiguration
這個自動化配置類,構造事務管理器。
@Transactional
不僅可以註解在方法上,也可以註解在類上。當註解在類上的時候意味着所有的public方法都是開啓事務的。
4.4 編寫測試用例
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceImplTest {
@Resource
private UserService userService;
@Before
public void setUp() {
// 準備,清空user表
userService.deleteAllUsers();
}
@Test
public void test() {
// 插入5個用戶
userService.create(User.builder().userName("a").password("123").phone("110").build());
userService.create(User.builder().userName("b").password("1234").phone("119").build());
userService.create(User.builder().userName("c").password("12345").phone("120").build());
userService.create(User.builder().userName("d").password("123456").phone("122").build());
userService.create(User.builder().userName("e").password("1234567").phone("135").build());
// 查數據庫,應該有5個用戶
Assert.assertEquals(5, userService.getAllUsers().intValue());
// 刪除兩個用戶
userService.deleteByName("a");
userService.deleteByName("e");
// 查數據庫,應該有5個用戶
Assert.assertEquals(3, userService.getAllUsers().intValue());
}
@Test
public void transactionalTest(){
// 插入5個用戶
userService.create(User.builder().userName("a").password("123").phone("110").build());
userService.create(User.builder().userName("b").password("1234").phone("119").build());
userService.create(User.builder().userName("c").password("12345").phone("120").build());
userService.create(User.builder().userName("d").password("123456").phone("122").build());
userService.create(User.builder().userName("e").password("1234567").phone("135").build());
User otherUser = User.builder().userName("f").password("12345678").phone("911").build();
// 查數據庫,應該有5個用戶
Assert.assertEquals(5, userService.getAllUsers().intValue());
userService.clearAdd(otherUser);
userService.create(User.builder().userName("a").password("123").phone("110").build());
// 查數據庫,應該有2個用戶
Assert.assertEquals(2, userService.getAllUsers().intValue());
UserService mockService = mock(UserServiceImpl.class);
when(mockService.create(otherUser)).thenThrow(new RuntimeException());
mockService.clearAdd(otherUser);
// 查數據庫,應該有2個用戶
Assert.assertEquals(2, userService.getAllUsers().intValue());
}
}
5 測試結果
請讀者動動手,運行測試用例test()
, transactionalTest()
6 工程目錄
7 結束語
本文是SpringBoot
操作數據庫的開篇,後續會介紹基於Mybatis
、JPA
、Mybatis Puls
的數據庫操作,已經基於Sharding Jdbc
分庫分表,讀寫分離操作,敬請期待,本文源碼。
歡迎關注博主公衆號,第一時間推送最新文章