Java 在packagesToScan属性时如何提及persistenceUnitName

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18882683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:52:49  来源:igfitidea点击:

How to mention persistenceUnitName when packagesToScan property

javaspringhibernatejpa

提问by Gopi

I have two datasources and two entityManagerFactory instance. I was trying to use the new feature of 3.1 (Bootstrapping JPA entityManagerFactory without persistence.xml by using packagesToScan property).

我有两个数据源和两个 entityManagerFactory 实例。我试图使用 3.1 的新功能(通过使用 packagesToScan 属性在没有 persistence.xml 的情况下引导 JPA entityManagerFactory)。

In order to use the right entity manager factory instance, i have to distinguish using Persistence unit name and defining the PU name in persistence.xml is stopping the spring package scanning feature.

为了使用正确的实体管理器工厂实例,我必须区分使用 Persistence 单元名称和在persistence.xml 中定义 PU 名称是停止 spring 包扫描功能。

How to give the PU name while using packagesToScan feature?

使用packagesToScan功能时如何给PU名称?

My question is more duplicate of Is there a way to give persistenceUnitName for Spring's LocalContainerEntityManagerFactoryBean without persistence.xml?

我的问题是有没有办法为 Spring 的 LocalContainerEntityManagerFactoryBean 提供persistenceUnitName 而没有persistence.xml?

I couldn't find the answer or comment on the above post. So reposting as new question.

我找不到上述帖子的答案或评论。所以重新发布为新问题。

回答by ikumen

If I understand your question correctly, you would like to set the name of the persistenceUnitbacking an EntityManagerFactory, when defined without a persistence.xml?

如果我正确理解您的问题,您想设置支持的名称persistenceUnitan EntityManagerFactory,当定义时没有persistence.xml?

When you declare the entityManagerFactory, there is a persistenceUnitName property that you can set. For example:

当您声明 entityManagerFactory 时,您可以设置一个 persistenceUnitName 属性。例如:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
  <property name="dataSource" ref="dataSource"/>

  <property name="persistenceUnitName" value="yourPersistenceUnitName"/>

  <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
  <property name="packagesToScan">
    <list>
      <value>..</value>
      ...
    </list>
  </property>
</bean>     

回答by Nath Papadacis

Yes you can. Here's an example that uses annotation configuration for Spring

是的你可以。下面是一个使用Spring注解配置的例子

I found it best to organise each datasource into a different package.
My package structure is:

我发现最好将每个数据源组织到不同的包中。
我的包结构是:

datasource
    |__ converters         <-- holds any custom attribute converters for JPA
    |__ default            <-- for default datasource
    |       |__ model      <-- contains entities for default datasource
    |       |__ repository <-- contains repositories for default datasource
    |__ anotherdatasource  <-- for second datasource
            |__ model      <-- contains entities for second datasource
            |__ repository <-- contains repositories for second datasource

Pick one of the datasources as the default and create a configuration class for it along the lines of...

选择其中一个数据源作为默认值,并按照以下方式为它创建一个配置类...

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", basePackages = { "com.example.datasource.default.repository" })
public class JpaDefaultDatasourceConfig {

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

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("dataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.example.datasource.default.model", "com.example.datasource.converters").persistenceUnit("mydefault").build();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

Then for each subsequent datasource create another configuration class along the lines of... (Note:the use of packages to separate entity/repository scanning and the naming convention used throughout)

然后为每个后续数据源创建另一个配置类...... 注意:使用包来分离实体/存储库扫描和整个使用的命名约定)

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "anotherEntityManagerFactory", transactionManagerRef = "anotherTransactionManager", basePackages = { "com.example.datasource.anotherdatasource.repository" })
public class JpaAnotherDatasourceConfig {

    @Bean(name = "anotherDataSource")
    @ConfigurationProperties(prefix = "another.datasource")
    public DataSource anotherDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean anotherEntityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("anotherDataSource") DataSource anotherDataSource) {
        return builder.dataSource(anotherDataSource).packages("com.example.datasource.anotherdatasource.model", "com.example.datasource.converters").persistenceUnit("anotherName").build();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager anotherTransactionManager(@Qualifier("anotherEntityManagerFactory") EntityManagerFactory anotherEntityManagerFactory) {
        return new JpaTransactionManager(anotherEntityManagerFactory);
    }
}

You can configure each datasource using the configuration prefix. For the two examples above you could configure them using

您可以使用配置前缀配置每个数据源。对于上面的两个示例,您可以使用

application.yml

应用程序.yml

## JPA configuration
# This is the configuration for default datasource created by spring
spring:
  datasource:
    url: jdbc:mysql://localhost/default
    username: foo
    password: bar
    driverClassName: com.mysql.jdbc.Driver
    test-on-borrow: true
    test-while-idle: true
    validation-query: select 1;
    # maxActive: 1

# This is the configuration for an additional datasource which we will create ourselves
 another:
  datasource:
    url: jdbc:mysql://localhost/another
    username: foo
    password: bar
    driverClassName: com.mysql.jdbc.Driver
    test-on-borrow: true
    test-while-idle: true
    validation-query: select 1;

You don't necessarily need to worry now about the names of the persistence units (although we did name them) because we've carefully separated entity managers to only look at their entities/repositories you can simply inject the applicable repository and use it without having to worry about it getting the wrong datasource. If you do need the persistence unit you can just ask for it by name @PersistenceUnit(name = "anotherDatasource")

您现在不必担心持久性单元的名称(尽管我们确实命名了它们),因为我们已经仔细分离实体管理器,只查看它们的实体/存储库,您可以简单地注入适用的存储库并使用它而无需不必担心它会得到错误的数据源。如果您确实需要持久性单元,您可以按名称要求@PersistenceUnit(name = "anotherDatasource")