SpringBoot 整合 JdbcTemplate(配置多数据源)

数据持久化有几个常见的方案,有 Spring 自带的 JdbcTemplate 、有 MyBatis,还有 JPA,在这些方案中,最简单的就是 Spring 自带的 JdbcTemplate 了,这个东西虽然没有 MyBatis 那么方便,但是比起最开始的 Jdbc 已经强了很多了,它没有 MyBatis 功能那么强大,当然也意味着它的使用比较简单,事实上,JdbcTemplate 算是最简单的数据持久化方案了

一、创建一个 SpringBoot 项目

选择基本的 Web 依赖,再记得选上 Jdbc 依赖,以及数据库驱动依赖即可
在这里插入图片描述
项目创建成功之后,记得添加 Druid 数据库连接池依赖(注意这里可以添加专门为 Spring Boot 打造的 druid-spring-boot-starter,而不是我们一般在 SSM 中添加的 Druid),所有添加的依赖如下:

<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.27</version><scope>runtime</scope>
</dependency>

在 application.properties 中提供数据的基本配置

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=UTF-8

二、CRUD测试

①、创建Bean

public class User {private Long id;private String username;private String address;//省略getter/setter
}

②、创建Service,注入JdbcTemplate

@Service
public class UserService {@AutowiredJdbcTemplate jdbcTemplate;
}

③、CRUD

JdbcTemplate 中,除了查询有几个 API 之外,增删改统一都使用 update 来操作,自己来传入 SQL 即可。
update 方法的返回值就是 SQL 执行受影响的行数

//简单添加
public int addUser(User user){return jdbcTemplate.update("insert into user (username,address) values (?,?);", user.getUsername(), user.getAddress());
}/**复杂添加:相当于完全使用了 JDBC 中的解决方案构建 PreparedStatement 时传入 Statement.RETURN_GENERATED_KEYS,然后传入 KeyHolder,最终从 KeyHolder 中获取刚刚插入数据的 id 保存到 user 对象的 id 属性中去
*/
public int addUser2(){KeyHolder keyHolder = new GeneratedKeyHolder();int update = jdbcTemplate.update(new PreparedStatementGreator(){@Overridepublic PreparedStatement createPreparedStatement(Connection connection) throws SQLException {PreparedStatement ps = connection.prepareStatement("insert into user (username,address) values (?,?);",Statement.RETURN_GENERATED_KEYS);ps.setString(1, user.getUsername());ps.setString(2, user.getAddress());return ps;}},keyHolder);user.setId(keyHolder.getKey().longValue());System.out.println(user);return update;
}
//删除
public int deleteUserById(Long id){return jdbcTemplate.update("delete from user where id = ?",id);
}
//改
public int updateUserById(User user){return jdbcTemplate.update("update user set username=?,address=? where id=?",user.getUsername(),user.getAddress(),user.getId());
}
/**查询的时候需要提供一个 RowMapper,就是需要自己手动映射,将数据库中的字段和对象的属性一一对应起来
*/
public List<User> getAllUsers(){return jdbcTemplate.query("select * from user",new RowMapper<User>(){@Overridepublic User mapRow(ResultSet resultSet, int i) throws SQLException {String username = resultSet.getString("username");String address = resultSet.getString("address");long id = resultSet.getLong("id");User user = new User();user.setAddress(address);user.setUsername(username);user.setId(id);return user;}});
}//如果数据库中的字段和对象属性的名字一模一样的话,有另外一个简单的方案
//查询时候传参也是使用占位符,这个和前文的一致
public List<User> getAllUser2(){return jdbcTemplate.query("select * from user",new BeanPropertyRowMapper<>(User.class));
}

==========================================================

多数据源

一、创建工程(选择 Web、Jdbc 以及 MySQL 驱动)
在这里插入图片描述

手动添加 Druid 依赖,由于这里一会需要开发者自己配置 DataSoruce,所以这里必须要使用 druid-spring-boot-starter 依赖,而不是传统的那个 druid 依赖。
因为 druid-spring-boot-starter 依赖提供了 DruidDataSourceBuilder 类,这个可以用来构建一个 DataSource 实例,而传统的 Druid 则没有该类。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.28</version><scope>runtime</scope>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version>
</dependency>

二、配置数据源

配置两个数据源

spring.datasource.one.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=utf-8
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.two.url=jdbc:mysql:///test02?useUnicode=true&characterEncoding=utf-8
spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource

加了 one 和 two 之后,这里的配置就没法被 SpringBoot 自动加载了(因为前面的 key 变了)
需要我们自己去加载 DataSource 了,此时,需要自己配置一个 DataSourceConfig,用来提供两个 DataSource Bean

@Configuration
public class DataSourceConfig{@Bean@ConfigurationProperties(prefix="spring.datasource.one")//@ConfigurationProperties 是 Spring Boot 提供的类型安全的属性绑定DataSource dsOne(){ //表示使用 spring.datasource.one 前缀的数据库配置去创建一个 DataSourcereturn DruidDataSourceBuilder.create().build();}@Bean@ConfigurationProperties(prefix="spring.datasource.two")DataSource dsTwo(){return DruidDataSourceBuilder.create().build();}
}

三、配置JdbcTemplate实例

每一个 JdbcTemplate 的创建都需要一个 DataSource,由于 Spring 容器中现在存在两个 DataSource,默认使用类型查找,会报错,因此加上 @Qualifier 注解,表示按照名称查找

@Configuration
public class JdbcTemplate{@BeanJdbcTemplate jdbcTemplateOne(@Qualifier("dsOne") DataSource dsOne){return new JdbcTemplate(dsOne);}@BeanJdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo") DataSource dsTwo){return new JdbcTemplate(dsTwo);}
}

四、测试

@RestController
public class HelloController{// @Autowired 注解加上 @Qualifier 注解,两者联合起来,实际上也是 byName@Autowired@Qualifier("jdbcTemplateOne")JdbcTemplate jdbcTemplateOne;//使用 @Resource 注解,直接通过 byName 的方式注入进来@Resource(name="jdbcTemplateTwo")JdbcTemplate jdbcTemplateTwo;@GetMapping("/user")public List<User> getAllUser(){List<User> list = jdbcTemplateOne.query("select * from t_user", new BeanPropertyRowMapper<>(User.class));return list;}@GetMapping("/user2")public List<User> getAllUser2() {List<User> list = jdbcTemplateTwo.query("select * from t_user", new BeanPropertyRowMapper<>(User.class));return list;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/197326.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

家电电器展示预约小程序的作用是什么

电器产品已经成为人们生活的必备品&#xff0c;如冰箱、电视机、洗衣机等&#xff0c;而这些产品的购买方式也很多&#xff0c;可以到线下门店购买&#xff0c;也可以到线上多个电商平台购买&#xff0c;如今互联网高速发展以及民众享受线上服务带来的便捷性&#xff0c;同时商…

windows环境搭建Zblog博客并发布上线公网可访问

文章目录 1. 前言2. Z-blog网站搭建2.1 XAMPP环境设置2.2 Z-blog安装2.3 Z-blog网页测试2.4 Cpolar安装和注册 3. 本地网页发布3.1. Cpolar云端设置3.2 Cpolar本地设置 4. 公网访问测试5. 结语 1. 前言 想要成为一个合格的技术宅或程序员&#xff0c;自己搭建网站制作网页是绕…

MySql操作

Mysql数据库项目学习笔记 1.条件查询后排序 (SELECT counter : 0) temp设定临时变量ORDER BY id ASC用于将id以升序形式进行排列 SELECTcounter : counter 1 AS ROW,username,type,content FROMtest_info,( SELECTcounter : 0 ) temp WHEREusername 2 AND type 3 ORDER BYi…

网络文件共享服务(ftp和nfs)和如果用局域网搭建yum仓库

存储类型 存储类型分三种 1.直连式存储&#xff1a;DAS 2.存储区域网络&#xff1a;SAN 3.网络附加存储&#xff1a;NAS FTP文件传输协议 软件要利用协议&#xff0c;协议时通过应用程序实现的 各协议端口 ftp &#xff1a;20&#xff08;数据&#xff09; 21&#xff0…

好的CRM系统有哪些核心能力?

CRM是企业管理的重要工具&#xff0c;可以维护管理客户关系&#xff0c;提高企业的核心竞争力。市场营销、销售、客户服务和技术支持等相关领域都需要用到CRM系统。那么一个好的CRM&#xff0c;最核心的能力有哪些&#xff1f; 1.销售自动化 这里简单介绍下销售自动化的功能&…

值得学习的演示文稿制作范例

1,在第一张幻灯片前插入1张新幻灯片,设置幻灯片大小为“全屏显示(16:9) ”;为整个演示文稿应用“离子会议室”主题,放映方式为“观众自行浏览”;除了标1题幻灯片外其它每张幻灯片中的页脚插入“晶泰来水晶吊坠”七个字。 2,第一张幻灯片的版式设置为“标题幻灯片”,主标题为“…

MPN在QM中的使用

此文章为机器翻译SAP BLOG 文章&#xff0c;原文地址&#xff1a;Manufacturer Part Profile in QM | SAP Blogs 目的&#xff1a;–材料管理 (MM) 组件支持从不同供应商采购制造商特定的零件或材料。如果您实施制造商零件编号 (MPN) 处理功能&#xff0c;您还可以在质量管理 …

采集淘宝天猫整店商品api(店铺列表、店铺所有商品)

返回数据&#xff1a;请求链接 {"items": {"shop_id": "336945718","page": "1","real_total_results": "75","total_results": "75","page_size": 10,"page_coun…

航测三维实景:创造更加真实和精细的虚拟环境

航测三维实景&#xff1a;创造更加真实和精细的虚拟环境 航测三维实景技术是一项以航空摄影测量为基础&#xff0c;结合计算机图像处理和显示技术的高精度三维实景重建方法。它以其独特的视角和真实感十足的体验&#xff0c;已经广泛应用于城市规划、土地资源管理、自然资源调查…

Maven环境配置

Maven环境配置 下载Maven 网址&#xff1a;https://maven.apache.org/download.cgi 如果你的系统是Windows的直接按照箭头指示下载即可 环境变量配置 配置环境变量&#xff1a;将 Maven 的安装目录添加到您的系统环境变量中。 右键点击“我的电脑”&#xff08;或“此电脑…

HashMap会用就行了?一文解决HashMap的底层问题

前言 我们的手机通讯录之所以能快速定位到特定联系人&#xff0c;就是因为它运用了HashMap底层的原理。手机通讯录将每个联系人的姓名作为键&#xff0c;电话号码作为对应的值&#xff0c;通过这个键值对的方式实现了快速的数据定位和获取。就像你通过关键字快速找到对应的联系…