Spring-boot-database-handling
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>
</dependency>
Gradleユーザーの場合、build.gradleファイルに以下の依存関係を追加します。
compile('com.h2database:h2')
H2データベースに接続するには、classpath src/main/resourcesディレクトリの下にschema.sqlファイルとdata.sqlファイルを作成する必要があります。
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-java</artifactId>
</dependency>
Gradleユーザーの場合、build.gradleファイルに次の依存関係を追加します。
compile('mysql:mysql-connector-java')
次に、示されているようにMySQLでデータベースとテーブルを作成します-
プロパティファイルユーザーの場合、application.propertiesファイルに次のプロパティを追加します。
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testOnBorrow = true
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.minEvictableIdleTimeMillis = 30000
spring.datasource.validationQuery = SELECT 1
spring.datasource.max-active = 15
spring.datasource.max-idle = 10
spring.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ファイルに次の依存関係を追加する必要があります。
<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依存関係をビルド構成ファイルに追加する必要があります。
次に、JdbcTemplateクラスを@Autowiredした場合、Spring Bootは自動的にデータベースに接続し、JdbcTemplateオブジェクトのデータソースを設定します。
@Autowired
JdbcTemplate jdbcTemplate;
Collection<Map<String, Object>> rows = jdbc.queryForList("SELECT QUERY");
@Repositoryアノテーションをクラスファイルに追加する必要があります。 @Repositoryアノテーションは、Spring Bootアプリケーションのデータベースリポジトリを作成するために使用されます。
@Repository
public class ProductServiceDAO {
}
複数のデータソース
1つのSpring Bootアプリケーションに「n」個のデータソースを保持できます。 ここに示す例は、Spring Bootアプリケーションで複数のデータソースを作成する方法を示しています。 次に、アプリケーションプロパティファイルに2つのデータソース構成の詳細を追加します。
プロパティファイルユーザーの場合、次のプロパティをapplication.propertiesファイルに追加します。
spring.dbProductService.driverClassName = com.mysql.jdbc.Driver
spring.dbProductService.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true
spring.dbProductService.username = root
spring.dbProductService.password = root
spring.dbProductService.testOnBorrow = true
spring.dbProductService.testWhileIdle = true
spring.dbProductService.timeBetweenEvictionRunsMillis = 60000
spring.dbProductService.minEvictableIdleTimeMillis = 30000
spring.dbProductService.validationQuery = SELECT 1
spring.dbProductService.max-active = 15
spring.dbProductService.max-idle = 10
spring.dbProductService.max-wait = 8000
spring.dbUserService.driverClassName = com.mysql.jdbc.Driver
spring.dbUserService.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect = true
spring.dbUserService.username = root
spring.dbUserService.password = root
spring.dbUserService.testOnBorrow = true
spring.dbUserService.testWhileIdle = true
spring.dbUserService.timeBetweenEvictionRunsMillis = 60000
spring.dbUserService.minEvictableIdleTimeMillis = 30000
spring.dbUserService.validationQuery = SELECT 1
spring.dbUserService.max-active = 15
spring.dbUserService.max-idle = 10
spring.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;
@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;