美文网首页
Spring Boot 入门系列(四) 使用JdbcTempla

Spring Boot 入门系列(四) 使用JdbcTempla

作者: 回文体文回 | 来源:发表于2019-07-29 22:08 被阅读0次

文章使用版本为 Spring Boot 2.1.x

前言

我们都知道直接使用jdbc访问数据库会写大量的模板代码,而真正的业务逻辑很少。为了解决这个问题,出现了很多ORM框架,比如Hibernate(全自动)、Mybatis(半自动)等,而今天我们要说的是Spring提供的一个非常轻量级的框架JdbcTemplate。

准备工作

数据库我们使用MySQL,首先我们先创建一个学习使用的数据库和表。

CREATE SCHEMA IF NOT EXISTS `spring_boot_learn` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

CREATE TABLE IF NOT EXISTS `spring_boot_learn`.`user` (
  `id` VARCHAR(37) NOT NULL COMMENT 'UUID',
  `username` VARCHAR(128) NOT NULL COMMENT '用户名',
  `age` INT(10) unsigned NOT NULL COMMENT '年龄',
  PRIMARY KEY (`id`)  COMMENT ''
  )
ENGINE = InnoDB
COMMENT = '用户表';

添加引用

在Spring boot项目中使用JdbcTemplate非常方便,只需要添加如下依赖即可。

<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>

然后在application.yml中添加数据库相关配置,如下所示

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/spring_boot_learn?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&autoReconnect=true&useSSL=true
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    hikari:
      minimum-idle: 2
      maximum-pool-size: 5
      max-lifetime: 60000

然后Spring boot会为我们自动创建两个Bean JdbcTemplateNamedParameterJdbcTemplate,具体代码可以参考JdbcTemplateAutoConfiguration.class,内容如下

@Configuration
@ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class JdbcTemplateAutoConfiguration {

    private final DataSource dataSource;

    public JdbcTemplateAutoConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean(JdbcOperations.class)
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(this.dataSource);
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
        return new NamedParameterJdbcTemplate(this.dataSource);
    }

}

访问数据库

现在我们就来分别使用JdbcTemplate和NamedParameterJdbcTemplate来访问数据库。

JdbcTemplate

使用jdbcTemplate访问数据库非常像直接使用PreparedStatement,具体示例如下

  • 新增
jdbcTemplate.update("insert into user ( id, username, age ) values ( ?, ?, ? ) ", id, username, age);
  • 删除
jdbcTemplate.update("delete from user where id = ?", id);
  • 更新
jdbcTemplate.update("update user set username = ?, age = ? where id = ?", username, age, id);
  • 查找
jdbcTemplate.queryForObject("select * from user where id = ?", new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
  • 查找列表
jdbcTemplate.query("select * from user where age = ?", new Object[]{age}, new BeanPropertyRowMapper<>(User.class));

NamedParameterJdbcTemplate

使用jdbcTemplate非常方便,但是也有一些缺点,比如,参数列表的顺序不能错乱,参数较少时没什么大问题,如果参数较多,就要十分注意。NamedParameterJdbcTemplate使用字符串来代替问号进行参数替换,这样就不用担心顺序的问题了,具体可以看下面的例子

  • 新增
User user = new User()
        .setId(id)
        .setUsername(username)
        .setAge(age);
BeanPropertySqlParameterSource parameters = new BeanPropertySqlParameterSource(user);
namedParameterJdbcTemplate.update("insert into user ( id, username, age ) values ( :id, :username, :age) ", parameters);
  • 删除
MapSqlParameterSource parameters = new MapSqlParameterSource()
        .addValue("id", id);
namedParameterJdbcTemplate.update("delete from user where id = :id", parameters);
  • 更新
User user = new User()
        .setId(id)
        .setUsername(username)
        .setAge(age);
BeanPropertySqlParameterSource parameters = new BeanPropertySqlParameterSource(user);
namedParameterJdbcTemplate.update("update user set username = :username, age = :age where id = :id", parameters);
  • 查找
MapSqlParameterSource parameters = new MapSqlParameterSource()
                .addValue("id", id);
namedParameterJdbcTemplate.queryForObject("select * from user where id = :id", parameters, new BeanPropertyRowMapper<>(User.class));
  • 查找列表
MapSqlParameterSource parameters = new MapSqlParameterSource()
                .addValue("age", age);
namedParameterJdbcTemplate.query("select * from user where age = :age", parameters, new BeanPropertyRowMapper<>(User.class));

数据源

由于我们没有配置连接池的类型,Spring boot 自动使用了 HikariDataSource。关于 Spring boot 自动为我们配置什么数据源,请参考 官方文档

如果我们想使用阿里巴巴开源的 Druid 该怎么配置呢?

使用Druid

我们只要加入一个依赖就可以了

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

然后我们再运行项目时,就会发现启动日志里有一条

INFO 40235 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited

就说明我们现在是使用Druid了。

当然我们在使用时应该对Druid做一些参数配置,比如

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/spring_boot_learn?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&autoReconnect=true&useSSL=true
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    druid:
      initial-size: 2
      min-idle: 2
      max-active: 5
      max-wait: 60000

如果你对Druid的参数不怎么了解,可以查看官方参考配置

完整示例

相关文章

网友评论

      本文标题:Spring Boot 入门系列(四) 使用JdbcTempla

      本文链接:https://www.haomeiwen.com/subject/bcbuzxtx.html