Spring Boot Learning (vii) Web applications use SPRING-DATA-JPA multiple data source configuration

Source: Internet
Author: User
Tags assert config
The configuration of the data source can be followed by the example of Spring boot Learning (vii) Web applications using the Datasourceconfig implementation of JdbcTemplate multiple data source configuration. Add the JPA configuration for the first data source, note the two notes where you specify the Entity entity and Repository defined location for the data source, and use @Primary to differentiate between the primary data source.
Package Com.xiaojingg;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.beans.factory.annotation.Qualifier;
Import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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.EntityManager;
Import Javax.sql.DataSource;
Import Java.util.Map; /** * Xiao into GG * * * @Configuration @EnableTransactionManagement @EnableJpaRepositories (EntityManagerfactoryref= "Entitymanagerfactoryprimary", transactionmanagerref= "Transactionmanagerprimary", BasePa ckages= {"COM.XIAOJINGG.DOMAIN.P"})//Set repository location public class Primaryconfig {@Autowired @Qualifier ("Primaryd

    Atasource ") Private DataSource Primarydatasource; @Primary @Bean (name = "Entitymanagerprimary") public Entitymanager Entitymanager (Entitymanagerfactorybuilder Build
    ER) {return entitymanagerfactoryprimary (builder). GetObject (). Createentitymanager (); @Primary @Bean (name = "Entitymanagerfactoryprimary") public Localcontainerentitymanagerfactorybean Entityma Nagerfactoryprimary (Entitymanagerfactorybuilder builder) {return builder. DataSource (primarydata Source). Properties (Getvendorproperties (Primarydatasource)). Packages ("Com.xiaojingg.domai
    N.P ")//sets the location of the entity class. Persistenceunit (" Primarypersistenceunit "). Build ();

  }  @Autowired private jpaproperties jpaproperties; Private map<string, string> getvendorproperties (DataSource DataSource) {return JPAPROPERTIES.GETHIBERNATEPR
    Operties (DataSource); @Primary @Bean (name = "Transactionmanagerprimary") public Platformtransactionmanager Transactionmanagerprim ary (Entitymanagerfactorybuilder builder) {return new Jpatransactionmanager entitymanagerfactoryprimary (builder). g
    Etobject ()); }

}
The new JPA configuration for the second data source is similar to the first data source, as follows:
Package Com.xiaojingg;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.beans.factory.annotation.Qualifier;
Import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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.EntityManager;
Import Javax.sql.DataSource;
Import Java.util.Map; /** * Xiao into the GG * * * @Configuration @EnableTransactionManagement @EnableJpaRepositories (entitymanagerfactoryref= "Entit
   Ymanagerfactorysecondary ",     Transactionmanagerref= "Transactionmanagersecondary", basepackages= {"COM.XIAOJINGG.DOMAIN.S"})//Set Reposito RY location public class Secondaryconfig {@Autowired @Qualifier ("Secondarydatasource") Private DataSource Secondaryda

    Tasource;
        @Bean (name = "Entitymanagersecondary") public entitymanager Entitymanager (Entitymanagerfactorybuilder builder) {
    return Entitymanagerfactorysecondary (builder). GetObject (). Createentitymanager (); @Bean (name = "Entitymanagerfactorysecondary") public Localcontainerentitymanagerfactorybean Entitymanagerfactor 
                Ysecondary (Entitymanagerfactorybuilder builder) {return builder. DataSource (Secondarydatasource)  . Properties (Getvendorproperties (Secondarydatasource)). Packages ("COM.XIAOJINGG.DOMAIN.S")
    Sets the location of the entity class. Persistenceunit ("Secondarypersistenceunit"). Build ();

 @Autowired private jpaproperties jpaproperties;   Private map<string, string> getvendorproperties (DataSource DataSource) {return Jpaproperties.gethibernat
    Eproperties (DataSource); @Bean (name = "Transactionmanagersecondary") Platformtransactionmanager transactionmanagersecondary (EntityManage
    Rfactorybuilder builder) {return new Jpatransactionmanager (Entitymanagerfactorysecondary (builder). GetObject ()); }
}
The primary data source is configured as a spring.datasource.primary, and the second data source is configured as the spring.datasource.secondary at the beginning of the configuration.
Package Com.xiaojingg;
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 Javax.sql.DataSource; /** * Xiao into GG * * @Configuration public class Datasourceconfig {@Bean (name = "Primarydatasource") @Qualifier ("Prim  Arydatasource ") @ConfigurationProperties (prefix=" spring.datasource.primary ") public datasource Primarydatasource ()
    {return datasourcebuilder.create (). build (); @Bean (name = "Secondarydatasource") @Qualifier ("Secondarydatasource") @Primary @ConfigurationProperties (prefix= "Spring.datasource.secondary") public datasource Secondarydatasource () {return Datasourcebuilder.crea
    Te (). build (); }

} 


After the above configuration is completed, the entity and data access objects for the primary data source are: COM.XIAOJINGG.DOMAIN.P, and the entity and data access interface for the secondary data source is located at: com.xiaojingg.domain.s. Create the user entity and the corresponding repository interface under these two package to create their own entity and data access interface master data source
Package COM.XIAOJINGG.DOMAIN.P;
Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.Id;

    /** * Xiao into GG * * @Entity public class User {@Id @GeneratedValue private Long Id;

    @Column (nullable = false) private String name;

    @Column (nullable = False) private Integer age;
        Public user () {} public user (String name, Integer age) {this.name = name;
    This.age = age;
    Public Long GetId () {return id;
    public void SetId (Long id) {this.id = ID;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public Integer Getage () {return age;
    public void Setage (Integer age) {this.age = age;

}} package com.xiaojingg.domain.p;
Import Org.springframework.data.jpa.repository.JpaRepository; /** * Xiao Jin GG * public interface USerrepository extends Jparepository<user, long> {} Create the message entity and the corresponding repository interface from the data source package

COM.XIAOJINGG.DOMAIN.S;
Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.Id;

    /** * Xiao into GG * * @Entity public class Message {@Id @GeneratedValue private Long Id;

    @Column (nullable = false) private String name;

    @Column (nullable = false) private String content;
        Public message () {} The public message (string name, string content) {this.name = name;
    this.content = content;
    Public Long GetId () {return id;
    public void SetId (Long id) {this.id = ID;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public String getcontent () {return content; public void SetContent (String content) {this.content = ContenT

}} package com.xiaojingg.domain.s;
Import Org.springframework.data.jpa.repository.JpaRepository; /** * Xiao into GG * * Public interface Messagerepository extends Jparepository<message, long> {}
Finally, test cases are used to validate data operations using these two configurations for different data sources:
Package Com.xiaojingg;
Import Com.xiaojingg.domain.p.user;
Import Com.xiaojingg.domain.p.userrepository;
Import Com.xiaojingg.domain.s.message;
Import Com.xiaojingg.domain.s.messagerepository;
Import Org.junit.Assert;
Import Org.junit.Before;
Import Org.junit.Test;
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; /** * Xiao Jin gg * * @RunWith (Springrunner.class) @SpringBootTest public class
   springbootstudydemo7springdatajpamoreapplicationtests {@Autowired private userrepository userrepository;

   @Autowired private Messagerepository messagerepository; @Before public void SetUp () {} @Test the public void Test () throws Exception {Userrepository.save (new Us
      ER ("AAA", 10));
      Userrepository.save (New User ("BBB", 20);
      Userrepository.save (New User ("CCC", 30)); Userrepository.save (NEW User ("ddd", 40));

      Userrepository.save (New User ("Eee", 50));

      Assert.assertequals (5, Userrepository.findall (). Size ());
      Messagerepository.save (New Message ("O1", "aaaaaaaaaa"));
      Messagerepository.save (New Message ("O2", "bbbbbbbbbb"));

      Messagerepository.save (New Message ("O3", "CCCCCCCCCC"));

   Assert.assertequals (3, Messagerepository.findall (). Size ()); }

}
Run Screenshots:




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.