重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

详解基于SpringBoot与SpringDataJPA的多数据源配置-创新互联

由于项目需要,最近研究了一下基于spring Boot与Spring Data JPA的多数据源配置问题。以下是传统的单数据源配置代码。这里使用的是Spring的Annotation在代码内部直接配置的方式,没有使用任何XML文件。

创新互联专注于宁城企业网站建设,成都响应式网站建设,商城网站建设。宁城网站建设公司,为宁城等地区提供建站服务。全流程专业公司,专业设计,全程项目跟踪,创新互联专业和态度为您提供的服务
@Configuration 
@EnableJpaRepositories(basePackages = "org.lyndon.repository") 
@EnableTransactionManagement 
@PropertySource("classpath:application.properties") 
public class JpaConfig { 
   
  private static final String DATABASE_DRIVER = "db.driver"; 
  private static final String DATABASE_URL = "db.url"; 
  private static final String DATABASE_USER = "db.user"; 
  private static final String DATABASE_PASSWORD = "db.password"; 
  private static final String PACKAGES_TO_SCAN = "packages.to.scan"; 
  private static final String HIBERNATE_DIALECT = "hibernate.dialect"; 
  private static final String HIBERNATE_SHOW_SQL = "hibernate.show.sql"; 
   
  @Resource 
  private Environment env; 
   
  @Bean 
  public DataSource dataSource() { 
    DruidDataSource source = new DruidDataSource(); 
    source.setDriverClassName(env.getRequiredProperty(DATABASE_DRIVER)); 
    source.setUrl(env.getRequiredProperty(DATABASE_URL)); 
    source.setUsername(env.getRequiredProperty(DATABASE_USER)); 
    source.setPassword(env.getRequiredProperty(DATABASE_PASSWORD)); 
    return source; 
  } 
   
  @Bean 
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); 
    factory.setDataSource(dataSource()); 
    factory.setPersistenceProviderClass(HibernatePersistenceProvider.class); 
    factory.setPackagesToScan(env.getRequiredProperty(PACKAGES_TO_SCAN)); 
    factory.setJpaProperties(hibernateProperties()); 
    factory.afterPropertiesSet(); 
    return factory; 
  } 
   
  @Bean 
  public PlatformTransactionManager transactionManager() { 
    JpaTransactionManager manager = new JpaTransactionManager(); 
    manager.setEntityManagerFactory(entityManagerFactory().getObject()); 
    return manager; 
  } 
   
  @Bean 
  public HibernateExceptionTranslator hibernateExceptionTranslator() { 
    return new HibernateExceptionTranslator(); 
  } 
   
  private Properties hibernateProperties() { 
    Properties properties = new Properties(); 
    properties.put(HIBERNATE_DIALECT, env.getRequiredProperty(HIBERNATE_DIALECT)); 
    properties.put(HIBERNATE_SHOW_SQL, env.getRequiredProperty(HIBERNATE_SHOW_SQL)); 
    return properties; 
  } 
   
} 

分享名称:详解基于SpringBoot与SpringDataJPA的多数据源配置-创新互联
当前地址:http://cqcxhl.com/article/jicij.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP