In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "the method of configuring JPA multiple data sources in Springboot 2.1.5". In daily operation, I believe that many people have doubts about the method of configuring JPA multiple data sources in Springboot 2.1.5. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "Springboot 2.1.5 configuration JPA multiple data sources". Next, please follow the editor to study!
Recently, I was studying sprinJpa. According to the online blog, I tried to match the multiple data sources of Jpa, but I found that because the version of springboot was too high, the demo on the Internet was not applicable, so it took a long time to find a solution. Now record the operation as follows.
I. Yml configuration spring: datasource: test1: driver-class-name: com.mysql.jdbc.Driver password: 123456 # url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false # springboot2.0 above jdbc-url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false username: root test2: driver-class-name: com.mysql.jdbc. Driver password: 123456 # url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false # springboot2.0 above jdbc-url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false username: root jpa: # # whether to print sql show-sql: true properties: hibernate: # specifies that the engine is Innodb dialect: org. Hibernate.dialect.MySQL5InnoDBDialect hbm2ddl: # create: the last generated table is deleted each time hibernate is loaded # then re-generate the new table according to your model class, even if there are no changes twice. # this is an important reason for the loss of database table data. # create-drop: each time the hibernate is loaded, the table is generated according to the model class, but the table is automatically deleted as soon as sessionFactory is closed. # update: the most commonly used attribute, the table structure is automatically established according to the model class when hibernate is loaded for the first time (as long as the database is established first), and the table structure is automatically updated according to the model class when hibernate is loaded later. Even if the table structure changes, the rows in the table still exist and the previous rows will not be deleted. It is important to note that when deployed to the server, the table structure will not be set up immediately, but only after the application is run for the first time. # validate: every time you load hibernate, verify that the database table structure is created, and only the tables in the database are compared. No new tables are created, but new values are inserted. Auto: update II. Register datasource to the spring container @ Configurationpublic class DataSourceConfig {@ Bean (name = "primaryDataSource") @ Primary @ Qualifier ("primaryDataSource") @ ConfigurationProperties (prefix = "spring.datasource.test1") public DataSource primaryDataSource () {System.out.println ("- primaryDataSource initialization -") Return DataSourceBuilder.create () .build ();} @ Bean (name = "secondaryDataSource") @ Qualifier ("secondaryDataSource") @ ConfigurationProperties (prefix = "spring.datasource.test2") public DataSource secondaryDataSource () {System.out.println ("- secondaryDataSource initialization -") Return DataSourceBuilder.create () .build ();}} III. Register jpa-related objects into the spring container
Data source 1:
@ Configuration@EnableTransactionManagement@EnableJpaRepositories (entityManagerFactoryRef= "entityManagerFactoryPrimary", transactionManagerRef= "transactionManagerPrimary", basePackages= {"com.czcstudy.springbootdemo.day1.dao.test1"}) / / set the location of Repository public class RepositoryPrimaryConfig {@ Autowired @ Qualifier ("primaryDataSource") private DataSource primaryDataSource; @ Autowired private JpaProperties jpaProperties; @ Autowired private HibernateProperties hibernateProperties @ Primary @ Bean (name = "entityManagerFactoryPrimary") public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {/ / most of the online articles are jpaProperties.getHibernateProperties (dataSource); you get the configuration map of hibernate directly, / / but this method seems to be abandoned in springboot2.0+, so this is changed here. Map properties = hibernateProperties.determineHibernateProperties (jpaProperties.getProperties (), new HibernateSettings ()); return builder.dataSource (primaryDataSource) .properties (properties) .packages ("com.czcstudy.springbootdemo.day1.bean.po") .build (); / / entity package path} @ Primary @ Bean (name = "transactionManagerPrimary") public PlatformTransactionManager transactionManagerPrimary (EntityManagerFactoryBuilder builder) {return new JpaTransactionManager (entityManagerFactoryPrimary (builder). GetObject ());}
Data source 2:
@ Configuration@EnableTransactionManagement@EnableJpaRepositories (entityManagerFactoryRef= "entityManagerFactorySecondary", transactionManagerRef= "transactionManagerSecondary", basePackages= {"com.czcstudy.springbootdemo.day1.dao.test2"}) / / set the location of Repository public class RepositorySecondaryConfig {@ Autowired @ Qualifier ("secondaryDataSource") private DataSource secondaryDataSource; @ Autowired private JpaProperties jpaProperties; @ Autowired private HibernateProperties hibernateProperties @ Bean (name = "entityManagerFactorySecondary") public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {/ / most of the online articles are jpaProperties.getHibernateProperties (dataSource); you get the configuration map of hibernate directly, / / but this method seems to be abandoned in springboot2.0+, so this is changed here. Map properties = hibernateProperties.determineHibernateProperties (jpaProperties.getProperties (), new HibernateSettings ()); return builder.dataSource (secondaryDataSource) .properties (properties) .packages ("com.czcstudy.springbootdemo.day1.bean.po") .build (); / / package path of the entity} @ Bean (name = "transactionManagerSecondary") public PlatformTransactionManager transactionManagerPrimary (EntityManagerFactoryBuilder builder) {return new JpaTransactionManager (entityManagerFactorySecondary (builder) .getObject ()) Use the spring transaction example @ Servicepublic class JpaTestServiceImpl implements JpaTestService {@ Autowired private UserJpaTest2Dao userRepository2; @ Override @ Transactional (value = "transactionManagerSecondary", rollbackFor = RuntimeException.class) public void test () {List userJpaTestList = userRepository2.findAll (); System.out.println (userJpaTestList);}}
The specified value is the name of the PlatformTransactionManager object registered earlier, which needs to be specified when there are multiple data sources.
5. Summary
This is how springboot2.1.5 configures jpa multi-data sources. Start the project. We can see
HikariPool connection pooling has been started, which is the default database connection pooling for springboot, so we don't configure connection pooling here.
At this point, the study on "Springboot 2.1.5 how to configure JPA multiple data sources" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.