春ブーツは、JPAを使用して複数のデータソースを統合します

入門

JPA(Javaの永続API)は、Java永続API、Javaの永続性基準は、Hibernateは永続化仕様の技術であり、そして春データJPAのHibernateをフレームごとにカプセル化されます。
春JPAは初めて、私はほとんどのコードのデータベースアクセスCURD基本的な機能が出てきたかについて記述する必要はありません、何かが単にアーティファクトであることを感じました。この記事では、我々は春ブーツJPAは、複数のデータソースを使用して統合する方法を紹介します。
開発環境:

  • 春のブート2.0.5
  • 春データJPA 2.0.5
  • MySQLの5.6
  • JDK 8
  • IDEA 2018.3
  • ウィンドウズ10

依存性の導入

まず、我々は春ブーツ紹介したいと思いますspring-boot-starter-data-jpa依存。

Mavenの設定:

   <dependency>
        <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>

Gradleの構成:

compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.5.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.5.RELEASE' compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.0.5.RELEASE' compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'

コンフィギュレーション・データ・ソース

春ブーツはapplication.propertiesまたはapplication.ymlファイル、構成アイテム属性の使用方法を提供します。私はapplication.ymlファイルを使用することに慣れていますので、私はちょうど文言のapplication.ymlファイルが一覧表示されます。

spring:
  datasource:
    product:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/product?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
      username: root
      password: test123$
    customer:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/customer?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull username: root password: test123$ jpa: generate-ddl: true

application.ymlファイルを設定した後、顧客と製品データベースのデータベース内に作成されます。

エンティティ(エンティティ)クラスを追加します。

顧客エンティティ:

package com.springboot.jpa.customer.models;

import javax.persistence.*;

@Entity
public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(unique = true, nullable = false) private String email; private String firstName; private String lastName; protected Customer() { } public Customer(String email, String firstName, String lastName) { this.email = email; this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer[id=%d, firstName='%s', lastName='%s',email='%s']", id, firstName, lastName, email); } public Integer getId() { return id; } public String getEmail() { return email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }

製品のエンティティ:

package com.springboot.jpa.product.models;

import javax.persistence.*;

@Entity
public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(nullable = false) private String code; private String name; private double price; protected Product() { } public Product(String code, String name, double price) { this.code = code; this.name = name; this.price = price; } @Override public String toString() { return String.format("Product[id=%d, code='%s', name='%s', price='%s']", id, code, name, price); } public int getId() { return id; } public String getCode() { return code; } public String getName() { return name; } public double getPrice() { return price; } } 

追加データウェアハウス(リポジトリ)クラス

お客様のリポジトリ:

package com.springboot.jpa.customer.repository;

import com.springboot.jpa.customer.models.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository public interface CustomerRepository extends JpaRepository<Customer, Integer> { }

製品のリポジトリ:

package com.springboot.jpa.product.repository;

import com.springboot.jpa.product.models.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository public interface ProductRepository extends JpaRepository<Product, Integer> { }

コンフィギュレーション(config)クラスを追加します。

クライアントの構成:

package com.springboot.jpa.customer.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "customerEntityManagerFactory", transactionManagerRef = "customerTransactionManager", basePackages = {"com.springboot.jpa.customer.repository"}) public class CustomerConfig { @Primary @Bean(name = "customerDataSource") @ConfigurationProperties(prefix = "spring.datasource.customer") public DataSource customerDataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean(name = "customerEntityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("customerDataSource") DataSource dataSource) { return builder.dataSource(dataSource).packages("com.springboot.jpa.customer.data").persistenceUnit("customer").build(); } @Primary @Bean(name = "customerTransactionManager") public PlatformTransactionManager customerTransactionManager(@Qualifier("customerEntityManagerFactory") EntityManagerFactory customerEntityManagerFactory) { return new JpaTransactionManager(customerEntityManagerFactory); } }

製品構成:

package com.springboot.jpa.product.config;


import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "productEntityManagerFactory", transactionManagerRef = "productTransactionManager", basePackages = {"com.springboot.jpa.product.repository"} ) public class ProductConfig { @Bean(name = "productDataSource") @ConfigurationProperties(prefix = "spring.datasource.product") public DataSource dataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "productEntityManagerFactory") public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("productDataSource") DataSource dataSource) { return builder.dataSource(dataSource).packages("com.springboot.jpa.product.data").persistenceUnit("product").build(); } @Bean(name = "productTransactionManager") public PlatformTransactionManager productTransactionManager(@Qualifier("productEntityManagerFactory") EntityManagerFactory productEntityManagerFactory) { return new JpaTransactionManager(productEntityManagerFactory); } }

プロジェクト構造:

src/main/java
- com.springboot.jpa
      - product
        - config
        - models
        - repository
      - customer
        - config
        - models
        - repository

テストクラスを追加します。

顧客テストクラスCustomerDataSourcesTests:

package com.springboot.jpa;

import com.springboot.jpa.customer.repository.CustomerRepository;
import com.springboot.jpa.customer.models.Customer;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest public class CustomerDataSourcesTests { @Autowired private CustomerRepository customerRepository; @Test @Transactional("customerTransactionManager") public void createCustomer() { Customer customer = new Customer("[email protected]", "Charles", "Zhang"); customer = customerRepository.save(customer); assertNotNull(customerRepository.findById(customer.getId())); assertEquals(customerRepository.findById(customer.getId()).get().getEmail(), "[email protected]"); } }

製品のテストカテゴリProductDataSourcesTests:

package com.springboot.jpa;

import com.springboot.jpa.product.models.Product;
import com.springboot.jpa.product.repository.ProductRepository;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import org.junit.Test; import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest public class ProductDataSourcesTests { @Autowired private ProductRepository productRepository; @Test @Transactional("productTransactionManager") public void createProduct() { Product product = new Product("10000", "Book", 80.0); product = productRepository.save(product); assertNotNull(productRepository.findById(product.getId())); } }

テスト

各テストの後、データベースを照会することによって、2つのクラスを実行します。
Customerテーブル:

mysql> SELECT * FROM customer;
+----+-------------------+-----------+----------+
| id | email             | firstName | lastName |
+----+-------------------+-----------+----------+
|  1 | [email protected] | Charles   | Zhang    |
+----+-------------------+-----------+----------+
1 row in set

製品表:

mysql> SELECT * FROM product;
+----+-------+------+-------+
| id | code  | name | price |
+----+-------+------+-------+
|  1 | 10000 | Book |    80 |
+----+-------+------+-------+
1 row in set

この記事のアドレス:春JPAブート統合データソースを複数使用して
場所を:春ブーツ- JPA

著者:チャールズチャン


出典:https://www.cnblogs.com/weisenz/


このサイトは、「使用しています帰属4.0国際記事で再現」クリエイティブ・コモンズの契約を、明確に著者とソースの位置を示しています。

 
分類 Javaの 春ブーツ

おすすめ

転載: www.cnblogs.com/xichji/p/11323448.html