一尘不染

我需要 persistence.xml中的元素?

hibernate

我有一个非常简单的persistance.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

    <persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
        <class>pl.michalmech.eventractor.domain.User</class>
        <class>pl.michalmech.eventractor.domain.Address</class>
        <class>pl.michalmech.eventractor.domain.City</class>
        <class>pl.michalmech.eventractor.domain.Country</class>

        <properties>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>

</persistence>

而且有效。

但是,当我删除<class>元素时,应用程序看不到实体(所有类都带有注释@Entity)。

是否有自动扫描@Entity类的机制?


阅读 256

收藏
2020-06-20

共1个答案

一尘不染

jar-file您可以使用persistence.xml 。从Java EE
5教程中

<persistence>
    <persistence-unit name="OrderManagement">
        <description>This unit manages orders and customers.
            It does not rely on any vendor-specific features and can
            therefore be deployed to any persistence provider.
        </description>
        <jta-data-source>jdbc/MyOrderDB</jta-data-source>
        <jar-file>MyOrderApp.jar</jar-file>
        <class>com.widgets.Order</class>
        <class>com.widgets.Customer</class>
    </persistence-unit>
</persistence>

该文件定义了一个名为的持久性单元OrderManagement,它使用JTA感知数据源jdbc/MyOrderDB。所述jar- fileclass元素指定管持久类:实体类,可嵌入类和超类映射。该jar- file元素指定JAR文件都包含持久化类管理的打包持久单元可见,而该class元素明确命名持久化类管理。

对于Hibernate,请看第二章。也可以进行设置和配置以获取更多详细信息。

编辑: 实际上,如果您不介意不符合规范,则Hibernate即使在Java
SE中也支持自动检测。为此,添加hibernate.archive.autodetection属性:

<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
  <!-- This is required to be spec compliant, Hibernate however supports
       auto-detection even in JSE.
  <class>pl.michalmech.eventractor.domain.User</class>
  <class>pl.michalmech.eventractor.domain.Address</class>
  <class>pl.michalmech.eventractor.domain.City</class>
  <class>pl.michalmech.eventractor.domain.Country</class>
   -->

  <properties>
    <!-- Scan for annotated classes and Hibernate mapping XML files -->
    <property name="hibernate.archive.autodetection" value="class, hbm"/>

    <property name="hibernate.hbm2ddl.auto" value="validate" />
    <property name="hibernate.show_sql" value="true" />
  </properties>
</persistence-unit>
2020-06-20