将实体从库引用到JPA中的另一个库

时间:2014-08-16 04:57:32

标签: java spring hibernate jpa persistent

我正在使用带有JPA的Hibernate 4.3.6.Final和带有Java配置的项目中的Spring 4.0.6.RELEASE。

我有两个jar文件。 module1.jar和module2.jar。 module1.jar有一些实体 和module2有一些实体。我不能使用module2.jar中的module1.jar实体 persistent.xml和

<jar-file>module1.jar</jar-file>

我正在使用

是否需要使用persistent.xml

entityManagerFactoryBean.setPackagesToScan(&#34; com.mydomain&#34;)扫描所有jar文件中的所有实体。

1 个答案:

答案 0 :(得分:1)

不,如果您使用persistence.xml配置Spring的entityManagerFactoryBean,则无需使用setPackagesToScan()

来自New Features and Enhancements in Spring 3.1

  

3.1.12没有persistence.xml的JPA EntityManagerFactory引导

     

在标准JPA中,持久性单元通过特定jar文件中的META-INF / persistence.xml文件定义,这些文件将依次搜索@Entity类。在许多情况下,persistence.xml不包含多个单元名称,并依赖于所有其他问题(例如要使用的DataSource等)的默认值和/或外部设置。因此,Spring 3.1提供了另一种选择:LocalContainerEntityManagerFactoryBean接受'packagesToScan'属性,指定要扫描@Entity类的基本包。这类似于AnnotationSessionFactoryBean的本机Hibernate设置的同名属性,也类似于Spring的常规Spring bean的组件扫描功能。 实际上,这允许无XML的JPA设置,只需要为实体扫描指定基础包:对于依赖于Spring bean的组件扫描的Spring应用程序来说,这是一个特别好的匹配,甚至可能使用基于代码的Servlet 3.0初始化程序进行自举。