In Java, we generally use JdbcTemplate, JPA, MyBatis and other data persistence solutions. Of course, the simplest is the JdbcTemplate that comes with Spring. Let ’s take a look at it together.
1. Introduce JdbcTemplate dependency
<!-- 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. Database configuration content
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. Get started
Create User.java class
@Data
public class User {
/**
* 主键id
*/
private long id;
/**
* 登录账号
*/
private String name;
/**
* 登录密码
*/
private String password;
/**
* 性别
*/
private int sex;
/**
* 年龄
*/
private int age;
}
The lombok plugin is used here, so the get, set, and toString methods can be omitted using the @Data annotation
Create UserDao.java data persistence layer
@Repository
public class User {
@Autowired
private JdbcTemplate jdbcTemplate;
...
}
@Repository, indicating that this class has the function of CRUD (addition, deletion, modification and inspection) of objects
@Autowired, automatically injected into JdbcTemplate
increase
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()});
}
The number of rows affected by the database is returned 1
delete
public int deleteUser(int id) {
String sql = "delete from user where id = ?";
return jdbcTemplate.update(sql, new Object[]{id});
}
change
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()});
}
check
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));
}
In addition to these basic usages, JdbcTemplate also supports other usages, such as calling stored procedures, etc. These are relatively easy, and are similar to Jdbc itself
4. Source code analysis
In the org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration class, we can see:
@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);
}
}
}
When DataSource and JdbcTemplate exist in the current class path, the class will be automatically configured. The JdbcTemplate method indicates that if the developer does not provide an instance of JdbcOperations, the system will automatically configure a JdbcTemplate Bean (JdbcTemplate is an implementation of the JdbcOperations interface )
If you find deficiencies in reading, please leave a message! ! !