java 如何在 JPA 2.0 中自动检测实体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16088112/
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-10-31 21:52:14  来源:igfitidea点击:

How to auto detect entities in JPA 2.0

javaspringjakarta-eejpa

提问by LuckyLuke

I am pretty sure that I used some sort of auto detection of beans annotated with @Entity in JPA 2.0 in the past but I am not able to find out how. How do you do that instead of listing each bean in a classXML element in the persistence.xml?

我很确定我过去在 JPA 2.0 中使用了某种用 @Entity 注释的 bean 的某种自动检测,但我不知道如何。您如何做到这一点而不是class在persistence.xml的XML 元素中列出每个bean ?

采纳答案by zagyi

Since Spring 3.1, you also have the option to forget persistence.xmlaltogether, and configure your EntityManagerFactoryusing the packagesToScanproperty, similar to this:

从 Spring 3.1 开始,您还可以选择完全忘记 persistence.xml,并配置您EntityManagerFactory使用的packagesToScan属性,类似于:

<bean id="entityManagerFactory" 
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
      p:dataSource-ref="dataSource"
      p:packagesToScan="${jpa.entity.packages}">

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
              p:showSql="${hibernate.show_sql}"/>
    </property>

    <property name="jpaProperties">
        <props>
            <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
        </props>
    </property>
</bean>

回答by Paul Vargas

You need add to the persistence.xmlthe next line:

您需要添加到persistence.xml下一行:

<exclude-unlisted-classes>false</exclude-unlisted-classes>

e.g.

例如

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" ...>
    <persistence-unit name="YourPU" ...>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="eclipselink.logging.level" value="ALL"/>
            <property name="eclipselink.ddl-generation" 
                value="drop-and-create-tables"/>
        </properties>
    </persistence-unit>
</persistence>

回答by Gab

See Pascal Thivent answer here : Do I need <class> elements in persistence.xml?

请参阅此处的 Pascal Thivent 回答:我需要persistence.xml 中的 <class> 元素吗?

you have different way to do it, but JPA itself does not support auto-scan. The simplest and cleanest way to reference your entities IMHO is to package your model in a jar and to reference it with <jar-file>MyModel.jar</jar-file>

你有不同的方法来做到这一点,但 JPA 本身不支持自动扫描。恕我直言,引用您的实体的最简单和最干净的方法是将您的模型打包在一个 jar 中并使用<jar-file>MyModel.jar</jar-file>