在 Java 中,我們一般使用 JdbcTemplate、JPA、MyBatis 等數據持久化方案,當然,最簡單的就是 Spring 自帶的 JdbcTemplate,下面我們就一起來看看吧
1、引入 JdbcTemplate 依賴
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- jdbc連接 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- lombok插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2、數據庫配置內容
spring:
# 數據庫配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true&characterEncoding=UTF-8
# springboot 2.0 整合了hikari ,據說這是目前性能最好的java數據庫連接池
hikari:
username: root
password: 123456
3、開始使用
創建 User.java 類
@Data
public class User {
/**
* 主鍵id
*/
private long id;
/**
* 登錄賬號
*/
private String name;
/**
* 登錄密碼
*/
private String password;
/**
* 性別
*/
private int sex;
/**
* 年齡
*/
private int age;
}
這裏使用了 lombok 插件,所以使用 @Data 註解可以省略了 get、set、toString 方法
創建 UserDao.java 數據持久層
@Repository
public class User {
@Autowired
private JdbcTemplate jdbcTemplate;
...
}
@Repository,表示這個類具有對對象進行CRUD(增刪改查)的功能
@Autowired,自動注入 JdbcTemplate
增
public int addUser(User user) {
String sql = "insert into user(name,password,sex,age) value(?,?,?,?)";
return jdbcTemplate.update(sql, new Object[]{user.getName(), user.getPassword(), user.getSex(), user.getAge()});
}
返回了數據庫受影響行數 1
刪
public int deleteUser(int id) {
String sql = "delete from user where id = ?";
return jdbcTemplate.update(sql, new Object[]{id});
}
改
public int updateUser(User user) {
String sql = "update user set name = ?,password = ?,sex = ?,age = ? where id = ?";
return jdbcTemplate.update(sql, new Object[]{user.getName(), user.getPassword(), user.getSex(), user.getAge(), user.getId()});
}
查
public List<User> listUser() {
String sql = "select id,name,password,sex,age from user where 1 = 1";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
}
除了這些基本用法之外,JdbcTemplate 也支持其他用法,例如調用存儲過程等,這些都比較容易,而且和 Jdbc 本身都比較相似
4、源碼分析
在 org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration 類中,我們可以看到:
@Configuration
@ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcTemplateAutoConfiguration {
@Configuration
static class JdbcTemplateConfiguration {
private final DataSource dataSource;
private final JdbcProperties properties;
JdbcTemplateConfiguration(DataSource dataSource, JdbcProperties properties) {
this.dataSource = dataSource;
this.properties = properties;
}
@Bean
@Primary
@ConditionalOnMissingBean(JdbcOperations.class)
public JdbcTemplate jdbcTemplate() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
JdbcProperties.Template template = this.properties.getTemplate();
jdbcTemplate.setFetchSize(template.getFetchSize());
jdbcTemplate.setMaxRows(template.getMaxRows());
if (template.getQueryTimeout() != null) {
jdbcTemplate
.setQueryTimeout((int) template.getQueryTimeout().getSeconds());
}
return jdbcTemplate;
}
}
@Configuration
@Import(JdbcTemplateConfiguration.class)
static class NamedParameterJdbcTemplateConfiguration {
@Bean
@Primary
@ConditionalOnSingleCandidate(JdbcTemplate.class)
@ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(
JdbcTemplate jdbcTemplate) {
return new NamedParameterJdbcTemplate(jdbcTemplate);
}
}
}
當前類路徑下存在 DataSource 和 JdbcTemplate 時,該類就會被自動配置,JdbcTemplate 方法則表示,如果開發者沒有自己提供一個 JdbcOperations 的實例的話,系統就自動配置一個 JdbcTemplate Bean(JdbcTemplate 是 JdbcOperations 接口的一個實現)
如您在閱讀中發現不足,歡迎留言!!!