Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to configure Jpa multiple data sources in SpringBoot

Shulou Source: shulou.com Published: 2022-06-02 10:13:03 10月03日 Update

In view of how to configure Jpa multiple data sources in SpringBoot, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

In the 1.application.yml file, configure the database source. Here primary is the master library and secondary is the slave library.

Server: port: 808 multiple data source configuration # primaryspring: primary: datasource: url: jdbc:mysql://127.0.0.1:3306/database1?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai username: root password: * driver-class-name: com.mysql.jdbc.Driver # secondary secondary: datasource: url: jdbc:mysql://127.0.0. 1:3306/database1?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai username: root password: * driver-class-name: com.mysql.jdbc.Driver jpa: hibernate: primary-dialect: org.hibernate.dialect.MySQL5Dialect secondary-dialect: org.hibernate.dialect.MySQL5Dialect open-in-view: true show-sql: true

two。 Create a Spring configuration class where the path to spring.primary.datasource refers to the configuration of the yml file.

@ Configurationpublic class DataSourceConfig {@ Bean (name = "primaryDataSource") @ Qualifier ("primaryDataSource") @ ConfigurationProperties (prefix= "spring.primary.datasource") public DataSource primaryDataSource () {return DataSourceBuilder.create () .build ();} @ Bean (name = "secondaryDataSource") @ Qualifier ("secondaryDataSource") @ Primary @ ConfigurationProperties (prefix= "spring.secondary.datasource") public DataSource secondaryDataSource () {return DataSourceBuilder.create () .build ();}}

3. Create configuration classes for master library and slave library respectively.

Note: the configuration of the dao package and the dao package, as well as the @ Primary annotation specify the main library.

Main library configuration class:

@ Configuration@EnableTransactionManagement@EnableJpaRepositories (entityManagerFactoryRef = "entityManagerFactoryPrimary", transactionManagerRef = "transactionManagerPrimary", basePackages = {"com.xxx.xxx.dao.primary"}) / / set the location of Repository public class PrimaryConfig {@ Autowired private JpaProperties jpaProperties; @ Autowired @ Qualifier ("primaryDataSource") private DataSource primaryDataSource @ Primary @ Bean (name = "entityManagerPrimary") public EntityManager entityManager (EntityManagerFactoryBuilder builder) {return entityManagerFactoryPrimary (builder) .getObject () .createEntityManager () } @ Primary @ Bean (name = "entityManagerFactoryPrimary") public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {return builder .dat aSource (primaryDataSource) .properties (getVendorProperties (primaryDataSource)) .entity ("com.infinitus.yunxiao_data.entity.primary") / / sets the location of the entity class .persistenceUnit ("primaryPersistenceUnit") .build () } private Map getVendorProperties (DataSource dataSource) {return jpaProperties.getHibernateProperties (dataSource);} @ Primary @ Bean (name = "transactionManagerPrimary") public PlatformTransactionManager transactionManagerPrimary (EntityManagerFactoryBuilder builder) {return new JpaTransactionManager (entityManagerFactoryPrimary (builder). GetObject ());}}

From the configuration class of the library:

@ Configuration@EnableTransactionManagement@EnableJpaRepositories (entityManagerFactoryRef = "entityManagerFactorySecondary", transactionManagerRef = "transactionManagerSecondary", basePackages = {"com.infinitus.yunxiao_data.dao.secondary"}) / / set the location of Repository public class SecondaryConfig {@ Autowired private JpaProperties jpaProperties; @ Autowired @ Qualifier ("secondaryDataSource") private DataSource secondaryDataSource; @ Bean (name = "entityManagerSecondary") public EntityManager entityManager (EntityManagerFactoryBuilder builder) {return entityManagerFactorySecondary (builder). GetObject (). CreateEntityManager () } @ Bean (name = "entityManagerFactorySecondary") public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {return builder .DataSource (secondaryDataSource) .properties (getVendorProperties (secondaryDataSource)) .persistent ("com.xxx.xxx.entity.secondary") / / sets the location of the entity class .persistenceUnit ("primaryPersistenceUnit") .build () } private Map getVendorProperties (DataSource dataSource) {return jpaProperties.getHibernateProperties (dataSource);} @ Bean (name = "transactionManagerSecondary") PlatformTransactionManager transactionManagerSecondary (EntityManagerFactoryBuilder builder) {return new JpaTransactionManager (entityManagerFactorySecondary (builder). GetObject ());}}

4. Create master and slave library dao classes respectively.

Master dao:

Repositorypublic interface PrimaryRepository extends JpaRepository {@ Query (value = "SELECT p FROM PrimaryEntity p") List queryList ();}

From dao:

Repositorypublic interface SecondaryRepository extends JpaRepository {@ Query (value = "SELECT p FROM SecondaryEntity p") List queryList ();}

5. Create master and slave library entity classes respectively.

Master entity:

@ Entity@Table (name = "holiday_scheme") @ EntityListeners (AuditingEntityListener.class) public class PrimaryEntity extends AbstractPersistable {@ Column (name = "date") public String date; @ Column (name = "hour") public String hour; @ Column (name = "holiday") public String holiday; @ Column (name = "holiday_explain") public String holiday_explain; public String getDate () {return date } public void setDate (String date) {this.date = date;} public String getHour () {return hour;} public void setHour (String hour) {this.hour = hour;} public String getHoliday () {return holiday;} public void setHoliday (String holiday) {this.holiday = holiday } public String getHoliday_explain () {return holiday_explain;} public void setHoliday_explain (String holiday_explain) {this.holiday_explain = holiday_explain } @ Override public String toString () {return "PrimaryEntity {" + "date='" + date +'\'+ ", hour='" + hour +'\'+ ", holiday='" + holiday +'\'+ ", holiday_explain='" + holiday_explain +'\'+'}';}}

From entity:

@ Entity@Table (name = "active_dashboards") @ EntityListeners (AuditingEntityListener.class) public class SecondaryEntity extends AbstractPersistable {@ Column (name = "dashboard_id") public String dashboard_id; @ Column (name = "user_id") public String user_id; @ Column (name = "order_index") public String order_index; public String getDashboard_id () {return dashboard_id } public void setDashboard_id (String dashboard_id) {this.dashboard_id = dashboard_id;} public String getUser_id () {return user_id;} public void setUser_id (String user_id) {this.user_id = user_id;} public String getOrder_index () {return order_index } public void setOrder_index (String order_index) {this.order_index = order_index } @ Override public String toString () {return "SecondaryEntity {" + "dashboard_id='" + dashboard_id +'\'+ ", user_id='" + user_id +'\'+ ", order_index='" + order_index +'\'+'}';}}

6.controller requests to get data from different databases.

@ RestController@RequestMapping ("/ database") public class MailController {private final Logger logger = LoggerFactory.getLogger (this.getClass ()); @ Autowired PrimaryRepository primaryRepository; @ Autowired SecondaryRepository secondaryRepository; @ RequestMapping ("/ primary") @ ResponseBody public String primary () {return primaryRepository.queryList (). ToString ();} @ RequestMapping ("/ secondary") @ ResponseBody public String secondary () {return secondaryRepository.queryList (). ToString ();}} attention

Here are two potholes encountered when configuring multiple data sources, which fall into the pit if you don't pay attention.

The 1.Application class does not need to configure the @ EnableJpaRepositories annotation and will report the following error.

A component required a bean named 'entityManagerFactory' that could not be f

two。 Pay attention to check the dao class, get the data in the correct format, whether there is a field that does not exist in the table, to avoid starting exceptions. As follows, there is no job_name field in the SecondaryEntity table, so comment out can start successfully, etc.

/ / @ Query (value = "SELECT p FROM SecondaryEntity p where p.job_name =? 1") / / List queryOdcRecord (String job_name); this is the answer to the question about how to configure Jpa multi-data sources in SpringBoot. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Tags: Configuration data source location location problem field entity database file method more comments help solution different easy successful easy two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Microsoft NVidia Xiaomi OPPO Reno