在Springboot

时间:2017-09-04 09:31:02

标签: java spring jpa spring-boot

我想在EntityManager中使用SpringBoot

应用

@Configuration
@EnableRetry // To enable Spring retry
@EnableJpaRepositories
@EnableAspectJAutoProxy(proxyTargetClass=true)
@SpringBootApplication
public class Application {

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

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }    
}

MailConfig

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "mailEntityManager",
        transactionManagerRef = "mailTransactionManager",
        basePackageClasses = MmcMonitoringLog.class)

public class MailConfig {

    @Autowired(required = false)
    private PersistenceUnitManager persistenceUnitManager;

    @Bean
    @ConfigurationProperties("app.order.jpa")
    public JpaProperties orderJpaProperties() {
        return new JpaProperties();
    }

    @Bean
    @ConfigurationProperties(prefix = "app.order.datasource")
    public DataSource orderDataSource() {
        return (DataSource) DataSourceBuilder.create().type(DataSource.class).build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean orderEntityManager(
            JpaProperties orderJpaProperties) {
        EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(orderJpaProperties);
        return builder
                .dataSource(orderDataSource())
                .packages(MmcMonitoringLog.class)
                .persistenceUnit("ordersDs")
                .build();
    }

    @Bean
    public JpaTransactionManager orderTransactionManager(EntityManagerFactory orderEntityManager) {
        return new JpaTransactionManager(orderEntityManager);
    }

    private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties customerJpaProperties) {
        JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(customerJpaProperties);
        return new EntityManagerFactoryBuilder(jpaVendorAdapter,
                customerJpaProperties.getProperties(), this.persistenceUnitManager);
    }

    private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) {
        AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(jpaProperties.isShowSql());
        adapter.setDatabase(jpaProperties.getDatabase());
        adapter.setDatabasePlatform(jpaProperties.getDatabasePlatform());
        adapter.setGenerateDdl(jpaProperties.isGenerateDdl());
        return adapter;
    }

}

MailService的

public class MailService extends TaskAdaptor implements Runnable {

    @Autowired
    MmcMonitoringLogRepository mmcMonitoringLogRepository;

    @Override
    public void run() {

   List<MmcMonitoringLog> list = mmcMonitoringLogRepository.findByMonitoringLog("1");
   ......
}

appication.properties

spring.datasource.url= jdbc:mysql://xxxx:3306/adb?autoReconnect=true&useSSL=false
spring.datasource.username=xxx
spring.datasource.password=xxx


# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = none

我尝试实现以下https://github.com/snicoll-demos/demo-multi-entity-managers/blob/master/src/main/java/demo/order/OrderConfig.java,但是我的SpringBoot立即停止而没有任何异常。如果我删除MailConfig,Springboot就可以启动了。问题是什么?我在正确的道路上吗?

3 个答案:

答案 0 :(得分:2)

我认为你没有设置数据源的值。您需要在application.properties中设置“app.order.jpa”和“app.order.datasource”属性才能使示例正常工作。

关于您可以在此处阅读的配置属性:

http://www.baeldung.com/configuration-properties-in-spring-boot

请参阅此处的示例:

https://github.com/snicoll-demos/demo-multi-entity-managers/blob/master/src/main/resources/application.properties

app.customer.datasource.url=jdbc:h2:mem:customers;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
app.customer.datasource.driver-class-name=org.h2.Driver
app.customer.jpa.properties.hibernate.hbm2ddl.auto=create

app.order.datasource.url=jdbc:h2:mem:orders;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
app.order.datasource.driver-class-name=org.h2.Driver
app.order.jpa.properties.hibernate.hbm2ddl.auto=create

答案 1 :(得分:2)

您不需要在Spring Boot中进行bean配置,它在内部管理这种类型的配置。 您可以像

一样使用JPA的EntityManagerFactory
@Autowired
 EntityManagerFactory emf;

答案 2 :(得分:1)

穆克什·达拉吉亚(Mukesh Dharajiya)的回答是:

@Autowired EntityManagerFactory factory;

private manageEntities(){

    // javadoc: Create a new application-managed EntityManager. 
    // This method returns a new EntityManager instance each time it is invoked. 
    EntityManager em = emFactory.createEntityManager();

}

编辑:实际上,您刚刚使用了LocalContainerEntityManagerFactoryBean,所以下面的信息可能不适用。

在您的解决方案中,您尝试创建一个将覆盖springboot已经自动配置的entityManagerFactory的bean。

对此我不是100%肯定,但我相信您需要这样做:

  1. 排除自动配置(在配置了jpa之前,@EnableJpaRepositories可能无法工作):
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class})
public class Application {
    public static void main(String[] args) {
        // Now spring will not autoconfigure jpa for you, so there should not already be a factory bean
        // If you do this you will need to implement all of the steps missed in the autoconfig to get jpa functioning again
        SpringApplication.run(Application.class, args);
    }
}
  1. (也许?-未测试),在属性中设置spring.main.allow-bean-definition-overriding=true或命名该bean,然后使用@Qualified自动装配它,以便您可以覆盖现有的工厂bean。