linux spring boot 连接mysql_Springboot(四十六)数据库源(连接数据库)

712a2a754714e754c265594a0c064162.png

Spring Boot为创建数据库的数据源提供了非常好的支持。不需要编写任何额外的代码来在Spring Boot中创建数据源(DataSource)。 只需添加依赖项并执行配置详细信息就足以创建DataSource并连接数据库。

在本章中,将使用Spring Boot JDBC驱动程序连接来连接数据库。

首先,需要在构建配置文件中添加Spring Boot Starter JDBC依赖项。

Maven用户可以在pom.xml 文件中添加以下依赖项。

org.springframework.boot spring-boot-starter-jdbc

Gradle用户可以在build.gradle 文件中添加以下依赖项。

compile('org.springframework.boot:spring-boot-starter-jdbc')

连接到H2数据库

要连接H2数据库,需要在构建配置文件中添加H2数据库依赖项。

对于Maven用户,请在pom.xml 文件中添加以下依赖项。

com.h2database h2

对于Gradle用户,请在build.gradle 文件中添加以下依赖项。

compile('com.h2database:h2')

需要在src/main/resources 目录下创建schema.sql 文件和data.sql 文件来连接H2数据库。

schema.sql 文件的内容如下所示。

CREATE TABLE PRODUCT (ID INT PRIMARY KEY, PRODUCT_NAME VARCHAR(25));

data.sql 文件的内容如下所示。

INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (1,'Honey');INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (2,'Almond');

连接MySQL

要连接MySQL数据库,需要将MySQL依赖项添加到我们的构建配置文件中。

对于Maven用户,请在pom.xml 文件中添加以下依赖项。

mysql mysql-connector-java

对于Gradle用户,请在build.gradle 文件中添加以下依赖项。

compile('mysql:mysql-connector-java')

现在,在MySQL中创建数据库和表,如图所示 -

a4e50e58bd09b244b41454fd5f55294d.png

对于属性文件用户,请在application.properties 文件中添加以下属性。

spring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = truespring.datasource.username = rootspring.datasource.password = rootspring.datasource.testOnBorrow = truespring.datasource.testWhileIdle = truespring.datasource.timeBetweenEvictionRunsMillis = 60000spring.datasource.minEvictableIdleTimeMillis = 30000spring.datasource.validationQuery = SELECT 1spring.datasource.max-active = 15spring.datasource.max-idle = 10spring.datasource.max-wait = 8000

对于YAML用户,请在application.yml 文件中添加以下属性。

spring: datasource:  driverClassName: com.mysql.jdbc.Driver url: "jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true" username: "root" password: "root" testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000

连接Redis

Redis是一个用于存储内存数据结构的开源数据库。 要在Spring Boot应用程序中连接Redis数据库,需要在构建配置文件中添加Redis依赖项。

Maven用户应在pom.xml 文件中添加以下依赖项。

org.springframework.boot spring-boot-starter-redis

Gradle用户应在build.gradle 文件中添加以下依赖项。

compile('org.springframework.boot:spring-boot-starter-data-redis')

对于Redis连接,需要使用RedisTemplate。 对于RedisTemplate,需要提供JedisConnectionFactory的详细信息。

@BeanJedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory jedisConFactory = new JedisConnectionFactory(); jedisConFactory.setHostName("localhost"); jedisConFactory.setPort(6000); jedisConFactory.setUsePool(true); return jedisConFactory;}@Beanpublic RedisTemplate redisTemplate() { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactory()); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); return template;}

现在自动连接RedisTemplate类并从Redis数据库访问数据。

@AutowiredRedisTemplate redis;Map datalist = redis.opsForHash().entries(“Redis_code_index_key”);

JdbcTemplate

要在Spring Boot应用程序中使用JdbcTemplate访问关系数据库,需要在构建配置文件中添加Spring Boot Starter JDBC依赖项。

然后,如果@Autowired JdbcTemplate类,Spring Boot会自动连接数据库并为JdbcTemplate对象设置数据源。

@AutowiredJdbcTemplate jdbcTemplate;Collection> rows = jdbc.queryForList("SELECT QUERY");

应将@Repository注释添加到类文件中。 @Repository注释用于为Spring Boot应用程序创建数据库存储库。

@Repositorypublic class ProductServiceDAO {}

多个数据源

可以在一个Spring Boot应用程序中保留’n’个数据源。 此处给出的示例显示了如何在Spring Boot应用程序中创建多个数据源。 例如,要在应用程序属性文件中添加两个数据源配置详细信息。

对于属性文件用户,请将以下属性添加到application.properties 文件中。

spring.dbProductService.driverClassName = com.mysql.jdbc.Driverspring.dbProductService.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = truespring.dbProductService.username = rootspring.dbProductService.password = rootspring.dbProductService.testOnBorrow = truespring.dbProductService.testWhileIdle = truespring.dbProductService.timeBetweenEvictionRunsMillis = 60000spring.dbProductService.minEvictableIdleTimeMillis = 30000spring.dbProductService.validationQuery = SELECT 1spring.dbProductService.max-active = 15spring.dbProductService.max-idle = 10spring.dbProductService.max-wait = 8000spring.dbUserService.driverClassName = com.mysql.jdbc.Driverspring.dbUserService.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect = truespring.dbUserService.username = rootspring.dbUserService.password = rootspring.dbUserService.testOnBorrow = truespring.dbUserService.testWhileIdle = truespring.dbUserService.timeBetweenEvictionRunsMillis = 60000spring.dbUserService.minEvictableIdleTimeMillis = 30000spring.dbUserService.validationQuery = SELECT 1spring.dbUserService.max-active = 15spring.dbUserService.max-idle = 10spring.dbUserService.max-wait = 8000

Yaml用户应该在application.yml 文件中添加以下属性。

spring: dbProductService:  driverClassName: com.mysql.jdbc.Driver url: "jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true" password: "root" username: "root" testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 dbUserService:  driverClassName: com.mysql.jdbc.Driver url: "jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true" password: "root" username: "root" testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1  max-active: 15 max-idle: 10 max-wait: 8000

现在,创建一个Configuration 类,为多个数据源创建DataSource和JdbcTemplate。

import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.jdbc.core.JdbcTemplate;@Configurationpublic class DatabaseConfig { @Bean(name = "dbProductService") @ConfigurationProperties(prefix = "spring.dbProductService") @Primary public DataSource createProductServiceDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "dbUserService") @ConfigurationProperties(prefix = "spring.dbUserService") public DataSource createUserServiceDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "jdbcProductService") @Autowired public JdbcTemplate createJdbcTemplate_ProductService(@Qualifier("dbProductService") DataSource productServiceDS) { return new JdbcTemplate(productServiceDS); } @Bean(name = "jdbcUserService") @Autowired public JdbcTemplate createJdbcTemplate_UserService(@Qualifier("dbUserService") DataSource userServiceDS) { return new JdbcTemplate(userServiceDS); }}

然后,使用@Qualifier注释自动连接JDBCTemplate对象。

@Qualifier("jdbcProductService")@AutowiredJdbcTemplate jdbcTemplate;@Qualifier("jdbcUserService")@AutowiredJdbcTemplate jdbcTemplate;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值