Spring Boot 資料庫處理



Spring Boot 提供了非常好的支援來建立資料庫的 DataSource。我們不需要編寫任何額外的程式碼來在 Spring Boot 中建立 DataSource。只需新增依賴項並進行配置細節就足以建立 DataSource 並連線資料庫。

在本章中,我們將使用 Spring Boot JDBC 驅動程式連線來連線資料庫。

首先,我們需要在我們的構建配置檔案中新增 Spring Boot Starter JDBC 依賴項。

Maven 使用者可以在 pom.xml 檔案中新增以下依賴項。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Gradle 使用者可以在 build.gradle 檔案中新增以下依賴項。

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

連線 H2 資料庫

要連線 H2 資料庫,我們需要在我們的構建配置檔案中新增 H2 資料庫依賴項。

對於 Maven 使用者,請在您的 pom.xml 檔案中新增以下依賴項。

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>

對於 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 檔案中新增以下依賴項。

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-j</artifactId>
   <scope>runtime</scope>
</dependency>

對於 Gradle 使用者,請在您的 build.gradle 檔案中新增以下依賴項。

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

現在,按照以下步驟在 MySQL 中建立資料庫和表:

Database and Tables in MySQL

對於 properties 檔案使用者,請在 application.properties 檔案中新增以下屬性。

spring.datasource.url = jdbc:mysql://:3306/PRODUCTSERVICE
spring.datasource.username = root
spring.datasource.password = root

對於 YAML 使用者,請在 application.yml 檔案中新增以下屬性。

spring:
   datasource: 
      url: "jdbc:mysql://:3306/PRODUCTSERVICE"
      username: "root"
      password: "root"

連線 Redis

Redis 是一個開源資料庫,用於儲存記憶體中的資料結構。要在 Spring Boot 應用程式中連線 Redis 資料庫,我們需要在我們的構建配置檔案中新增 Redis 依賴項。

Maven 使用者應該在您的 pom.xml 檔案中新增以下依賴項。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

Gradle 使用者應該在您的 build.gradle 檔案中新增以下依賴項。

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

對於 Redis 連線,我們需要使用 RedisTemplate。對於 RedisTemplate,我們需要提供 JedisConnectionFactory 的詳細資訊。

@Bean
JedisConnectionFactory jedisConnectionFactory() {
   JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();
   jedisConFactory.setHostName("localhost");
   jedisConFactory.setPort(6000);
   jedisConFactory.setUsePool(true);
   return jedisConFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
   RedisTemplate<String, Object> 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 資料庫訪問資料。

@Autowired
RedisTemplate<String, Object> redis;
Map<Object,Object> datalist = redis.opsForHash().entries(“Redis_code_index_key”);

JDBCTemplate

要在 Spring Boot 應用程式中使用 JdbcTemplate 訪問關係資料庫,我們需要在我們的構建配置檔案中新增 Spring Boot Starter JDBC 依賴項。

然後,如果您 `@Autowired` 了 JdbcTemplate 類,Spring Boot 會自動連線資料庫併為 JdbcTemplate 物件設定 Datasource。

@Autowired
JdbcTemplate jdbcTemplate;
Collection<Map<String, Object>> rows = jdbc.queryForList("SELECT QUERY");

`@Repository` 註解應該新增到類檔案中。`@Repository` 註解用於為您的 Spring Boot 應用程式建立資料庫資源庫。

@Repository
public class ProductServiceDAO {
}

多個 DataSource

我們可以在單個 Spring Boot 應用程式中保留 'n' 個 DataSource。這裡給出的示例展示瞭如何在 Spring Boot 應用程式中建立多個數據源。現在,在 application.properties 檔案中新增兩個資料來源的配置詳細資訊。

對於 properties 檔案使用者,請將以下屬性新增到您的 application.properties 檔案中。

spring.dbProductService.url = jdbc:mysql://:3306/PRODUCTSERVICE
spring.dbProductService.username = root
spring.dbProductService.password = root

spring.dbUserService.url = jdbc:mysql://:3306/USERSERVICE
spring.dbUserService.username = root
spring.dbUserService.password = root

YAML 使用者應該在您的 application.yml 檔案中新增以下屬性。

spring:
   dbProductService: 
      url: "jdbc:mysql://:3306/PRODUCTSERVICE?autoreconnect=true"
      password: "root"
      username: "root"
   dbUserService: 
      url: "jdbc:mysql://:3306/USERSERVICE?autoreconnect=true"
      password: "root"
      username: "root"

現在,建立一個配置類來為多個數據源建立 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;

@Configuration
public 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")
@Autowired
JdbcTemplate jdbcTemplate;

@Qualifier("jdbcUserService")
@Autowired
JdbcTemplate jdbcTemplate;
廣告