programing

persistence.xml에 요소가 필요합니까?

sourcejob 2022. 12. 3. 00:33
반응형

persistence.xml에 요소가 필요합니까?

매우 간단한 persion.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수??

에는 persistence.xml이 .jar-file사용할 수 있습니다.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-file ★★★★★★★★★★★★★★★★★」class요소는 관리 대상 지속성 클래스(엔티티 클래스, 내장 가능 클래스 및 매핑된 슈퍼 클래스)를 지정합니다.jar-file는 관리 이 요소는 JAR 파일을 지정합니다.class요소는 명시적으로 관리 대상 지속성 클래스에 이름을 지정합니다.

휴지 상태의 경우는, 제2장을 참조해 주세요. 상세한 것에 대하여는, 셋업과 설정도 참조해 주세요.

편집: 실제로 사양에 준거하고 있지 않은 경우, 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>

Java SE 환경에서는 지정한 대로 모든 클래스를 지정해야 합니다.

Java SE 환경에서 명명된 모든 관리 지속성 클래스 목록을 지정하여 이동성을 보장해야 합니다.

그리고.

지속성 유닛의 루트에 포함된 주석이 달린 지속성 클래스를 지속성 유닛에 포함시키지 않을 경우 exclude-unlisted-classes 요소를 사용해야 합니다.exclude-unlisted-classes 요소는 Java SE 환경에서 사용할 수 없습니다.

(JSR-000220 6.2.1.6)

Java EE 환경에서는 공급자가 주석을 검색하므로 이 작업을 수행할 필요가 없습니다.

해 볼 수 .<exclude-unlisted-classes>false</exclude-unlisted-classes>internancy.xml로 합니다.로 " " " 입니다.false와 EE로true이클립스링크탑링크 모두 이 기능을 지원하고 있습니다.단, 상기와 같이 SE에서 동작하는 것에 의존해서는 안 됩니다.

다음을 시험해 볼 수 있습니다(SE 환경에서는 동작하거나 동작하지 않을 수 있습니다).

<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
     <exclude-unlisted-classes>false</exclude-unlisted-classes>

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

persistence.xml에 클래스 요소가 필요합니까?

아니, 꼭 그렇지는 않아.Eclipse에서 수행하는 방법은 다음과 같습니다(Kepler 테스트 완료).

프로젝트를 마우스 오른쪽 버튼으로 클릭하고 속성을 클릭한 다음 Persistence 클래스 관리 체크박스에서 주석이 달린 클래스 자동 검색 체크박스에서 JPA를 선택합니다.

여기에 이미지 설명 입력

JPA를 하고 있는 사용자는 3.1 JPA를 설정할 수 .packagesToScan property の under under の under 。LocalContainerEntityManagerFactoryBean완전히 합니다.

여기 내막이야

하다, 준비하다, 하다.jar-file컴파일된 클래스가 있는 폴더의 요소 경로.예를 들어 persistence.xml을 준비할 때 다음과 같은 내용을 일부 통합 테스트에 추가했습니다.

 <jar-file>file:../target/classes</jar-file>

JPA 2+의 경우는, 이것이 유효합니다.

 <jar-file></jar-file>

전쟁 중인 모든 병을 스캔하여 주석이 달린 @Entity 클래스를 찾습니다.

hibern hibern hibern hibern hibern hibern hibern hibern hibern 。<exclude-unlisted-classes>false</exclude-unlisted-classes>(TopLink eclipseEclipseLink 및 、 EclipseLink 。

클래스 목록을 persistence.xml로 자동 생성하는 툴이 있습니다.예를 들어 IntelliJ의 Import Database Schema 마법사입니다.persistence.xml에서 프로젝트의 초기 클래스를 취득하면 프로젝트 진행에 따라 수동으로 하나의 클래스를 추가하거나 삭제할 수 있습니다.

제가 하고 있는 것과 비슷한 것을 하고 있는지는 모르겠지만, 저는 Maven을 사용하여 별도의 컴포넌트에서 JAXB를 사용하여 XSD에서 소스 자바 로드를 생성합니다.이 아티팩트를 "기본 모델"이라고 합니다.

Java 소스를 포함하는 이 아티팩트를 Import하여 "base-model" 아티팩트 jar의 모든 클래스에서 휴지 상태를 실행하고 각 아티팩트를 명시적으로 지정하지 않고 실행하려고 했습니다.휴지 상태 컴포넌트의 의존관계로서 「base-model」을 추가하고 있습니다만, 문제는 persistence.xml 의 태그에 의해서, 절대 패스만을 지정할 수 있는 것입니다.

제가 찾은 방법은 "base-model" jar 의존성을 타겟 dir에 정확하게 복사하고 버전도 삭제하는 것입니다.따라서 "base-model" 아티팩트를 빌드하면 "base-model-1.0-SNAPSHOT.jar"가 생성되지만 복사 리소스 단계에서는 "base-model.jar"로 복사됩니다.

그래서 동면 컴포넌트를 위한 폼에는 다음과 같습니다.

            <!-- We want to copy across all our artifacts containing java code
        generated from our scheams. We copy them across and strip the version
        so that our persistence.xml can reference them directly in the tag
        <jar-file>target/dependency/${artifactId}.jar</jar-file> -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.5.1</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                </execution>
            </executions>       
            <configuration>
                <includeArtifactIds>base-model</includeArtifactIds>
                <stripVersion>true</stripVersion>
            </configuration>        
        </plugin>

다음으로 다음 단계의 휴지 상태 플러그인을 "process-classes"라고 부릅니다.

            <!-- Generate the schema DDL -->
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>hibernate3-maven-plugin</artifactId>
            <version>2.2</version>

            <executions>
                <execution>
                    <id>generate-ddl</id>
                    <phase>process-classes</phase>
                    <goals>
                        <goal>hbm2ddl</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <components>
                    <component>
                        <name>hbm2java</name>
                        <implementation>annotationconfiguration</implementation>
                        <outputDirectory>/src/main/java</outputDirectory>
                    </component>
                </components>
                <componentProperties>
                    <persistenceunit>mysql</persistenceunit>
                    <implementation>jpaconfiguration</implementation>
                    <create>true</create>
                    <export>false</export>
                    <drop>true</drop>
                    <outputfilename>mysql-schema.sql</outputfilename>
                </componentProperties>
            </configuration>
        </plugin>

마지막으로 persistence.xml에서 다음과 같이 jar의 위치를 명시적으로 설정할 수 있습니다.

<jar-file>target/dependency/base-model.jar</jar-file>

속성을 추가합니다.

<property name="hibernate.archive.autodetection" value="class, hbm"/>

이는 해결책이 아니라 Spring을 사용하는 사용자를 위한 힌트입니다.

사용하려고 했습니다.org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean「」를 해 주세요.persistenceXmlLocation 나는 지 the the the the the the the the the the the the the the the but<class>persistenceXmlLocation 가리키다META-INF/persistence.xml를 참조해 주세요.

사용하지 않을 때persistenceXmlLocation 것은 할 수 있다<class>★★★★★★★★★★★★★★★★★★.

이 솔루션이 사양에 맞는지는 모르겠지만 다른 사람들과 공유할 수 있을 것 같습니다.

의존성 트리

마이스터항아리

엔티티 클래스만 포함됩니다.아니요.META-INF/persistence.xml.

my-services.항아리

에 따라 다름my-entities. EJB만 포함됩니다.

마이스터항아리

에 따라 다름my-services. 리소스 클래스와META-INF/persistence.xml.

문제

  • 어떻게 하면<jar-file/>에 요소를 넣다.my-resources임시 종속성의 버전 고정 아티팩트 이름으로 사용할 수 있습니까?
  • 어떻게 하면<jar-file/>요소의 값과 실제 과도 종속성의 값을 비교합니다.

해결 방법

직접 종속성 및 리소스 필터링

나는 재산과 의존을 넣었다.my-resources/pom.xml.

<properties>
  <my-entities.version>x.y.z-SNAPSHOT</my-entities.version>
</properties>
<dependencies>
  <dependency>
    <!-- this is actually a transitive dependency -->
    <groupId>...</groupId>
    <artifactId>my-entities</artifactId>
    <version>${my-entities.version}</version>
    <scope>compile</scope> <!-- other values won't work -->
  </dependency>
  <dependency>
    <groupId>...</groupId>
    <artifactId>my-services</artifactId>
    <version>some.very.sepecific</version>
    <scope>compile</scope>
  </dependency>
<dependencies>

지금 바로 입수할 수 있습니다.persistence.xml걸러질 준비가 되어 있다

<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
  <persistence-unit name="myPU" transaction-type="JTA">
    ...
    <jar-file>lib/my-entities-${my-entities.version}.jar</jar-file>
    ...
  </persistence-unit>
</persistence>

Maven Enforcer 플러그인

를 사용하여dependencyConvergence규칙, 우리는 확실히 할 수 있다.my-entities' 버전은 직접 버전과 추이 버전 모두 동일합니다.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>1.4.1</version>
  <executions>
    <execution>
      <id>enforce</id>
      <configuration>
        <rules>
           <dependencyConvergence/>
        </rules>
      </configuration>
      <goals>
        <goal>enforce</goal>
      </goals>
    </execution>
  </executions>
</plugin>

모든 경우에 그렇지는 않다.

Jboss 7.0.8과 Eclipselink 2.7.0을 사용하고 있습니다.persistence.xml에 추가하지 않고 엔티티를 로드하기 위해 Jboss Standalone XML에 다음 시스템 속성을 추가했습니다.

<property name="eclipselink.archive.factory" value="org.jipijapa.eclipselink.JBossArchiveFactoryImpl"/>

언급URL : https://stackoverflow.com/questions/1780341/do-i-need-class-elements-in-persistence-xml

반응형