Menggunakan @EnableAutoConfiguration dan application.properties:
Contoh aplikasi.sifat:
# Primary Data Source spring.datasource.url=jdbc:h2:mem:default spring.datasource.username=sa spring.datasource.password= # Additional Data Source additional.datasource.url=jdbc:h2:mem:additional additional.datasource.username=anotheruser additional.datasource.password=anotherpassword
Contoh Kelas Konfigurasi untuk Sumber Data Utama:
<code class="java">@Configuration @EnableTransactionManagement @EnableAutoConfiguration @EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager", basePackages = {"com.example.repository.primary"}) public class PrimaryDataSourceConfig { @Bean public EntityManagerFactory entityManagerFactory() { // Create and configure EntityManagerFactory manually } @Bean public PlatformTransactionManager transactionManager() { // Create and configure PlatformTransactionManager manually } }</code>
Contoh Kelas Konfigurasi untuk Sumber Data Tambahan:
<code class="java">@Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "additionalEntityManagerFactory", transactionManagerRef = "additionalTransactionManager", basePackages = {"com.example.repository.additional"}) public class AdditionalDataSourceConfig { @Value("${additional.datasource.url}") private String url; @Value("${additional.datasource.username}") private String username; @Value("${additional.datasource.password}") private String password; @Bean public DataSource additionalDataSource() { // Create and configure DataSource manually } @Bean public EntityManagerFactory additionalEntityManagerFactory() { // Create and configure EntityManagerFactory manually } @Bean public PlatformTransactionManager additionalTransactionManager() { // Create and configure PlatformTransactionManager manually } }</code>
Contoh Kelas Perkhidmatan dengan Anotasi Transaksi:
<code class="java">@Service @Transactional("transactionManager") // Use primary transaction manager public class PrimaryService { // ... } @Service @Transactional("additionalTransactionManager") // Use additional transaction manager public class AdditionalService { // ... }</code>
Pendekatan ini memberikan kawalan dan fleksibiliti yang lebih besar apabila bekerja dengan berbilang sumber data dalam aplikasi Spring Boot.
Atas ialah kandungan terperinci Bagaimana untuk Mengkonfigurasi dan Menggunakan Berbilang Sumber Data dalam Spring Boot dengan Spring Data JPA?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!