這篇文章主要介紹了Spring Boot+Jpa多數據源配置的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
我們一直強調成都網站制作、網站設計、外貿網站建設對于企業(yè)的重要性,如果您也覺得重要,那么就需要我們慎重對待,選擇一個安全靠譜的網站建設公司,企業(yè)網站我們建議是要么不做,要么就做好,讓網站能真正成為企業(yè)發(fā)展過程中的有力推手。專業(yè)網站設計公司不一定是大公司,創(chuàng)新互聯(lián)作為專業(yè)的網絡公司選擇我們就是放心。
步驟
1.application.yml文件中,配置數據庫源。這里primary是主庫,secondary是從庫。
server: port: 8089 # 多數據源配置 #primary spring: 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
2.創(chuàng)建一個Spring配置類,其中spring.primary.datasource的路徑參考yml文件的配置。
@Configuration public 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.分別創(chuàng)建主庫、從庫的配置類。
注意:entity包和dao包的配置,以及@Primary注解指定主庫。
主庫配置類:
@Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactoryPrimary", transactionManagerRef = "transactionManagerPrimary", basePackages = {"com.infinitus.yunxiao_data.dao.primary"}) //設置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 .dataSource(primaryDataSource) .properties(getVendorProperties(primaryDataSource)) .packages("com.infinitus.yunxiao_data.entity.primary") //設置實體類所在位置 .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()); } }
從庫的配置類:
@Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactorySecondary", transactionManagerRef = "transactionManagerSecondary", basePackages = {"com.infinitus.yunxiao_data.dao.secondary"}) //設置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)) .packages("com.infinitus.yunxiao_data.entity.secondary") //設置實體類所在位置 .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.分別創(chuàng)建主、從庫dao類。
主dao:
@Repository public interface PrimaryRepository extends JpaRepository<PrimaryEntity, Long> { @Query(value = "SELECT p FROM PrimaryEntity p") List<PrimaryEntity> queryList(); }
從dao:
@Repository public interface SecondaryRepository extends JpaRepository<SecondaryEntity, Long> { @Query(value = "SELECT p FROM SecondaryEntity p") List<SecondaryEntity> queryList(); }
5.分別創(chuàng)建主、從庫entity類。
主entity:
@Entity @Table(name = "holiday_scheme") @EntityListeners(AuditingEntityListener.class) public class PrimaryEntity extends AbstractPersistable<Long> { @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 + '\'' + '}'; } }
從entity:
@Entity @Table(name = "active_dashboards") @EntityListeners(AuditingEntityListener.class) public class SecondaryEntity extends AbstractPersistable<Long> { @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請求獲取不同數據庫的數據。
@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(); } }
注意
下面提兩個在配置多數據源時遇到的坑點,一不注意就掉坑了。
1.Application類不需要配置@EnableJpaRepositories注解,會報如下錯誤。
A component required a bean named 'entityManagerFactory' that could not be f
2.注意檢查dao類,獲取數據的方法上格式是否正確,有沒有某個字段是表中不存在的,避免啟動異常。如下,SecondaryEntity表中是不存在job_name字段的,所以注釋掉才能啟動成功等。
//@Query(value = "SELECT p FROM SecondaryEntity p where p.job_name = ?1") //List<SecondaryEntity> queryOdcRecord(String job_name);
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Spring Boot+Jpa多數據源配置的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關知識等著你來學習!
分享文章:SpringBoot+Jpa多數據源配置的示例分析
文章起源:http://jinyejixie.com/article42/gdpchc.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)網站制作、網站排名、響應式網站、品牌網站建設、電子商務、網站營銷
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)