首页 > 其他分享 >对比Spring Boot中的JdbcClient与JdbcTemplate

对比Spring Boot中的JdbcClient与JdbcTemplate

时间:2024-01-31 13:32:59浏览次数:29  
标签:JdbcClient customer int Spring Boot jdbcTemplate jdbcClient lastname id

本文我们一起看看Spring Boot中 JdbcClientJdbcTemplate 之间的差异。

以下内容使用的Java和Spring Boot版本为:

  • Java 21
  • Spring Boot 3.2.1

假设我们有一个ICustomerService接口:

public interface ICustomerService {
    
    List<Customer> getAllCustomer();

    Optional<Customer> getCustomerById(int id);

    void insert(Customer customer);

    void update(int id, Customer customer);
    
    void delete(int id);
}

其中,涵盖了我们常见的数据CRUD操作。

下面就来一起看看,分别使用 JDBC ClientJDBC Template 的实现。

初始化对比

JdbcTemplate的初始化:

private final JdbcTemplate jdbcTemplate;

public CustomerJdbcTemplateService(JdbcTemplate jdbcTemplate){
  this.jdbcTemplate = jdbcTemplate;
}

JdbcClient的初始化;

private final JdbcClient jdbcClient;

public CustomerJdbcClientService(JdbcClient jdbcClient){
  this.jdbcClient = jdbcClient;
}

增删改查的实现对比

如果您学习过程中如遇困难?可以加入我们超高质量的Spring技术交流群,参与交流与讨论,更好的学习与进步!更多Spring Boot教程可以点击直达!,欢迎收藏与转发支持!

查询的实现对比

getAllCustomer查询返回集合数据的实现对比:

// jdbcTemplate实现
private final RowMapper<Customer> rowMapper = (rs, row)
     -> new Customer(rs.getInt("id"), rs.getString("name"), rs.getString("lastname"), rs.getDate("birthday"));

public List<Customer> getAllCustomer() {
  return jdbcTemplate.query("select id, name, lastname, birthday from customer", rowMapper);
}

// jdbcClient实现
public List<Customer> getAllCustomer(){
  return jdbcClient.sql("select id, name, lastname, birthday from customer").query(Customer.class).list();
}

getCustomerById查询返回单条数据的实现对比:

// jdbcTemplate实现
public Optional<Customer> getCustomerById(int id) {
  Customer customer = null;
  try {
    customer = jdbcTemplate.queryForObject("select id, name, lastname, birthday from customer where id = ?", rowMapper,  id );
  } catch (DataAccessException ex){
    LOG.error("Data not found. Id parameter: " + id, ex);
  }
  return Optional.ofNullable(customer);
}

// jdbcClient实现
public Optional<Customer> getCustomerById(int id){
  return jdbcClient.sql("select id, name, lastname, birthday from customer where id= :id")
                   .param("id", id)
                   .query(Customer.class)
                   .optional();
}

insert插入数据的实现对比

// jdbcTemplate实现
public void insert(Customer customer) {
  int inserted = jdbcTemplate.update("insert into customer (id, name, lastname, birthday) values (?,?,?,?)",
                 customer.id(), customer.name(), customer.lastname(),customer.birthday());
  Assert.state(inserted == 1 , "An exception error occurred while inserting customer");
}

// jdbcClient实现
public void insert(Customer customer){
  int inserted = jdbcClient.sql("insert into customer (id, name, lastname, birthday) values (?,?,?,?)")
                .params(List.of(customer.id(), customer.name(), customer.lastname(), customer.birthday()))
                .update();
  Assert.state(inserted == 1 , "An exception error occurred while inserting customer");
}

update更新数据的实现对比

// jdbcTemplate实现
public void update(int id, Customer customer) {
  int updated = jdbcTemplate.update("update customer set name = ?, lastname = ?, birthday = ? where id = ? ",
                customer.name(), customer.lastname(),customer.birthday(), id);
  Assert.state(updated == 1 , "An exception error occurred while updating customer");
}

// jdbcClient实现
public void update(int id, Customer customer){
  int updated = jdbcClient.sql("update customer set name = ?, lastname = ?, birthday = ? where id = ?")
                .params(List.of(customer.name(), customer.lastname(), customer.birthday(), id))
                .update();
  Assert.state(updated == 1, "An exception error occurred while updating customer");
}

delete删除数据的实现对比

// jdbcTemplate实现
public void delete(int id) {
  int deleted = jdbcTemplate.update("delete from customer where id = ?", id);
  Assert.state(deleted == 1 , "An exception error occurred while deleting customer");
}

// jdbcClient实现
public void delete(int id) {
  int deleted = jdbcClient.sql("delete from customer where id = :id").param("id",id).update();
  Assert.state(deleted == 1, "An exception error occurred while updating customer");
}

总结

上面我们分别演示了JdbcClientJdbcTemplate从初始化到真正执行增删改查操作的代码样例。总体上来说,JdbcClient的实现更为简洁方便。如果不考虑其他ORM框架的情况下,在未来的Spring Boot版本中,我会更偏向于选择JdbcClient来操作数据库。那么您觉得怎么样呢?留言区一起聊聊~

感谢您的阅读,也欢迎关注我的公众号:程序猿DD,专注分享Java领域的干货知识与最前沿的技术资讯。

标签:JdbcClient,customer,int,Spring,Boot,jdbcTemplate,jdbcClient,lastname,id
From: https://blog.51cto.com/u_13736395/9508395

相关文章

  • createDelegatingPasswordEncoder只有在spring 5.1.13才能用吗?
    springboot和spring版本对应关系:SpringBoot1.x支持SpringFramework4.x系列,包括4.0、4.1、4.2和4.3等版本。SpringBoot2.x支持SpringFramework5.x系列,包括5.0、5.1和5.2等版本。 下载springboot会一并下载 ......
  • Java21 + SpringBoot3整合springdoc-openapi,自动生成在线接口文档,支持SpringSecurity
    目录前言相关技术简介OpenAPISwaggerSpringfoxspringdocswagger2与swagger3常用注解对比实现步骤引入maven依赖修改配置文件设置api-docs和swagger-ui访问权限定义springdoc配置类修改Controller类和实体类查看效果总结前言近日心血来潮想做一个开源项目,目标是做一款可以适配多......
  • springboot~logback控制日志文件大小与历史个数
    日志本地化,对于每个应用来说都是必须的,最起码第一时间日志是需要本地化的,然后从本地化的日志中再进行推送,例如通过fluentd将日志推到es里,通过kibana工具进行可视化分析。日志文件大小限制对于把日志持久化到磁盘,你需要设置它的占用空间,logback提供了保存文件大小和历史文件数量......
  • Spring 事务管理 基于配置文件
    事务概念:原子性:要么都成功,有一个失败都失败一致性:总量不变(A有100元,B有100元,总量是200元。A把100元转给B,B就有了200元,总量还是200元)隔离性:两人操作同一条数据,不会相互影响持久性:最终提交到数据库后成功搭建事务操作环境进行操作():银行转账例子:1.1、创建数据库,创建表,添加......
  • SpringBoot、SpringCloud相关技术
    一、三层架构 1.1统一业务处理1.2解决三层架构中的结偶,使用了Ioc(控制反转)和DI(依赖注入) 1.3切面编程、事务处理、全局异常处理、Cookie、Session、JWT令牌、阿里云OSS、Mybatis处理数据库二、技术分类说明  2.1SSM三、Web总结四、相关第三方插件https://www......
  • SpringBoot自定义注解+反射实现 excel 导入的数据组装及字段校验
    本次给大家带来的SpringBoot中通过自定义注解+反射实现excel导入数据组装及字段校验的实现方式。这种实现方式其实是很普通、常规的方法,但很多同学在开发过程中,可能却不太容易想到他。当然我也是众多同学中的一员。1背景在前段时间的开发工作中,接手了一个很简单,很普通的开发任务。......
  • 在@KafkaListener启动之前需要做数据的预加载,该在Spring生命周期的哪个阶段做这个事情
    背景说明1、在Spring中消费Kafka数据时,最便捷的方法就是给方法加@KafkaListener注解。在数据消费逻辑中,需要先把一些配置信息预加载到内存中。有同事就提了一个问题:如果保证在消费者执行前,预加载数据的代码一定能执行完?也就是说,要等待数据预加载完成之后,再执行消费逻辑。大部分......
  • Mybatis-plus分页查询(SpringBoot)
    2024-01-30OS:Windows10 22H2IDE:IDEA2022.2.5JDKversion:19Mavenversion:3.6.3数据库:MySQL8.1.0mybatis-plus:3.5.3.1 一、在springBoot启动类中将分页插件加入到ioc容器里面启动类 @SpringBootApplication@MapperScan("com.ssm.mapper")publicclassMain{......
  • springboot集成mqtt
    SpringBoot集成MQTT(简单版)一、docker安装emqx环境(Linux系统)emqx:mqtt服务器(broker)version:'3'services:emqx:image:emqx/emqxcontainer_name:emqxrestart:alwaysports:-8001:18083-8002:1883-8003:8083-8004......
  • springboot项目启动时候初始化一些数据
    最近在看缓存预热的问题的时候,其中有一种解决方法,就是在项目启动的时候就自动加载到缓存中那缓存我就不说了,就关于项目启动的时候,可以初始化一些数据,以下为两种初始化的方式,可以参考1、编写类去实现ApplicationRunner接口,实现run()方法。2、编写类去实现CommandLineRunner接口,......