添加第二个数据源 - SpringBoot RepositoryRestService PersistenceConfig

时间:2014-11-02 19:18:43

标签: java spring-boot spring-data-jpa

我试图找到向我们的应用程序添加第二个数据源的最佳方法。主要目的是通过rest,&amp ;;暴露CRUD操作对数据库。需要针对第二个数据库进行身份验证和角色管理。我们没有使用XML配置。

有没有办法简单地在现有的PersistenceConfig.java文件中添加第二个数据源bean,还是需要复制第二个数据库实例的整个配置类?

申请表:

包foo;

import foo.config.PersistenceConfig;
import foo.config.RepositoryRestConfig;
import foo.config.WebConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@ComponentScan
@EnableJpaRepositories
@Import({PersistenceConfig.class, WebConfig.class, RepositoryRestConfig.class})
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

回购:

package foo.repository;

import foo.Widget;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

@RepositoryRestResource(collectionResourceRel = "widgets", path = "widgets")
public interface WidgetsRepository extends CrudRepository<Widget, Long> {
    List<Widget> findByWidgetId(@Param("widgetid") long widgetId);
}   

持久性配置:

package foo.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.PersistenceContext;
import javax.sql.DataSource;


@Configuration
@Import(RepositoryRestMvcConfiguration.class)
@EnableJpaRepositories
@EnableTransactionManagement

public class PersistenceConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabase(Database.SQL_SERVER);
        vendorAdapter.setShowSql(true);

        final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("foo.model");
        factory.setDataSource(dataSource());
        return factory;
    }

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        dataSource.setUrl("jdbc:sqlserver://127.0.0.1:1433;databaseName=fooDB");
        dataSource.setUsername("sa");
        dataSource.setPassword("*******");
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnReturn(true);
        dataSource.setTestWhileIdle(true);
        dataSource.setTimeBetweenEvictionRunsMillis(1800000L);
        dataSource.setNumTestsPerEvictionRun(3);
        dataSource.setMinEvictableIdleTimeMillis(1800000L);
        dataSource.setValidationQuery("SELECT 1");
        return dataSource;
    }


    @Bean
    public JpaDialect jpaDialect() {
        return new HibernateJpaDialect();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return txManager;
    }

}

感谢您的协助......

2 个答案:

答案 0 :(得分:0)

查看@Qualifier注释。使用此批注,您可以定义相同类型的各种bean并为其分配名称。它等同于id XML标记中的bean参数。

这是relevant part of Spring documentation

答案 1 :(得分:0)

首先,值得注意的是,PersistenceConfig中的几乎所有配置都是多余的,因为Spring Boot会自动为您配置它。几乎是非默认的,你需要指定的是你的DataSource配置,例如SQLServer URL。

有一个section in the documentation,介绍了如何使用@Primaryapplication.properties配置两个数据源:

  

创建多个数据源与创建第一个数据源的工作方式相同。如果您使用JDBC或JPA的默认自动配置(那么任何@Autowired注入都将使用它),您可能希望将其中一个标记为@Primary。“

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.primary")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix="datasource.secondary")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}

然后,您可以使用application.properties以及datasource.primarydatasource.secondary前缀配置这两个数据源:

例如:

datasource.primary.jdbcUrl=jdbc:sqlserver://127.0.0.1:1433;databaseName=fooDB
datasource.primary.user=sa
datasource.primary.password=secret

datasource.primary.jdbcUrl=jdbc:sqlserver://127.0.0.1:1433;databaseName=barDB
datasource.primary.user=sa
datasource.primary.password=secret