在SpringBoot中目前流行的持久層操作工具是Mybatis Plus。
Mybatis Plus 使用參考:SpringBoot整合Mybatis-Plus
但是在SpringBoot中還内置了一款持久層操作工具JDBC Template,它比Mybatis Plus操作上更加繁瑣,不建議使用。
但是在有的老項目上還在使用,有需要的可以了解一下。
引入Starter
在SpringBoot的pom檔案中引入JDBC Template的Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
配置資料源參數
在application.properties中配置資料庫連接配接參數。
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/baex
spring.datasource.username=root
spring.datasource.password=rootroot
注入JDBCTemplate對象
在需要使用持久化操作的地方通過@Autowired注解注入JDBC Template對象。
@Autowired
JdbcTemplate jdbcTemplate;
查詢資料
使用JDBC Template對象的query對象查詢資料庫,傳入要執行的SQL語句和RowMapper對象。
String sql = "select role_id, role_name from sys_role";
List<Role> result = jdbcTemplate.query(sql, rowMapper);
RowMapper是将查詢結果封裝到實體類中,需要自己實作封裝的操作。
如下是将查詢結果封裝到Role實體類中,其實就是用set方法将字段值設定到Role的對象中。
RowMapper<Role> rowMapper = new RowMapper<Role>() {
@Override
public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
Role role = new Role();
role.setRoleId(rs.getInt("role_id"));
role.setRoleName(rs.getString("role_name"));
return role;
}
};
更新和删除相對更簡單一點,通過update方法執行對應的SQL就可以。
完整代碼
@SpringBootTest
public class JDBCT {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void testJDBC(){
String sql = "select role_id, role_name from sys_role";
RowMapper<Role> rowMapper = new RowMapper<Role>() {
@Override
public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
Role role = new Role();
role.setRoleId(rs.getInt("role_id"));
role.setRoleName(rs.getString("role_name"));
return role;
}
};
List<Role> result = jdbcTemplate.query(sql, rowMapper);
System.out.println(result);
}
}
其他配置
在applcation.properties中還提供了JDBC Template的配置項可供選擇。
# 一次fetch操作擷取的資料行數
spring.jdbc.template.fetch-size=-1
# 查詢最大行數
spring.jdbc.template.max-rows=1000
# 逾時時間,預設機關是秒
spring.jdbc.template.query-timeout=100000