JPA 엔티티 메타모델 생성 방법
CriteriaQuery JPA 2.0에는 엔티티의 메타모델 표현을 지원하는 API도 있습니다.
(메타모델 클래스를 수동으로 만드는 것이 아니라 메타모델을 생성하기 위해) 이 API의 완전한 기능 구현에 대해 알고 있는 사람이 있습니까?Eclipse에서 이것을 설정하는 단계도 알고 있다면 정말 좋을 것입니다(주석 프로세서를 설정하는 것만큼 간단하다고 생각합니다만, 혹시 모르실 수도 있습니다).
편집: 방금 Hibernate JPA 2 Metamodel Generator를 발견했습니다.단, jar 다운로드 링크를 찾을 수 없기 때문에 문제는 해결되지 않습니다.
편집 2: 이 질문을 한 지 한참 지났습니다만, 다시 돌아와서 SourceForge의 Hibernate JPA Model Generator 프로젝트에 대한 링크를 추가하려고 합니다.
Eclipse에서의 셋업 순서도 알고 있으면 좋을 것 같습니다(주석 프로세서를 셋업하는 것만큼이나 간단하다고 생각합니다만, 혹시 모르실지도 모릅니다).
네.다양한 JPA 2.0 구현의 구현 및 지침을 다음에 나타냅니다.
이클립스 링크
휴지 상태
org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor- http://in.relation.to/2009/11/09/hibernate-static-metamodel-generator-annotation-processor
 
Open JPA
org.apache.openjpa.persistence.meta.AnnotationProcessor6- http://openjpa.apache.org/builds/2.4.1/apache-openjpa/docs/ch13s04.html
 
데이터핵
org.datanucleus.jpa.JPACriteriaProcessor- http://www.datanucleus.org/products/accessplatform_2_1/jpa/jpql_criteria_metamodel.html
 
최신의 휴지 상태 실장은, 다음의 Web 사이트에서 입수할 수 있습니다.
오래된 휴지 상태 구현은 다음과 같습니다.
jpa-metamodels-with-maven-예시를 봐주세요.
휴지 상태
- 는 필요하다
org.hibernate.org:hibernate-jpamodelgen. - 는 「」입니다.
org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor. 
의존관계로서 휴지 상태
    <dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-jpamodelgen</artifactId>
      <version>${version.hibernate-jpamodelgen}</version>
      <scope>provided</scope>
    </dependency>
 
프로세서로 휴지 상태
      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <compilerArguments>-AaddGeneratedAnnotation=false</compilerArguments> <!-- suppress java.annotation -->
              <processors>
                <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
              </processors>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>${version.hibernate-jpamodelgen}</version>
          </dependency>
        </dependencies>
      </plugin>
 
Open JPA
- 는 필요하다
org.apache.openjpa:openjpa. - 는 「」입니다.
org.apache.openjpa.persistence.meta.AnnotationProcessor6. -  요소가 한 것 .OpenJPA 는는 pa pa pa pa pa pa pa pa pa pa 。
<openjpa.metamodel>true<openjpa.metamodel>. 
의존관계로서의 Open JPA
  <dependencies>
    <dependency>
      <groupId>org.apache.openjpa</groupId>
      <artifactId>openjpa</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <compilerArgs>
            <arg>-Aopenjpa.metamodel=true</arg>
          </compilerArgs>
        </configuration>
      </plugin>
    </plugins>
  </build>
 
프로세서로서의 Open JPA
      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <id>process</id>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.apache.openjpa.persistence.meta.AnnotationProcessor6</processor>
              </processors>
              <optionMap>
                <openjpa.metamodel>true</openjpa.metamodel>
              </optionMap>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
            <version>${version.openjpa}</version>
          </dependency>
        </dependencies>
      </plugin>
 
이클립스 링크
- 는 필요하다
org.eclipse.persistence:org.eclipse.persistence.jpa.modelgen.processor. - 는 「」입니다.
org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor. - 에는 Eclipse Link가 필요합니다.
persistence.xml. 
종속 요소로서의 Eclipse Link
  <dependencies>
    <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
      <scope>provided</scope>
    </dependency>
 
프로세서로서의 Eclipse Link
    <plugins>
      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
              </processors>
              <compilerArguments>-Aeclipselink.persistencexml=src/main/resources-${environment.id}/META-INF/persistence.xml</compilerArguments>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>${version.eclipselink}</version>
          </dependency>
        </dependencies>
      </plugin>
 
데이터핵
- 는 필요하다
org.datanucleus:datanucleus-jpa-query. - 는 「」입니다.
org.datanucleus.jpa.query.JPACriteriaProcessor. 
의존관계로서의 Data Nucleus
  <dependencies>
    <dependency>
      <groupId>org.datanucleus</groupId>
      <artifactId>datanucleus-jpa-query</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>
 
프로세서로서의 Data Nucleus
      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <id>process</id>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.datanucleus.jpa.query.JPACriteriaProcessor</processor>
              </processors>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-jpa-query</artifactId>
            <version>${version.datanucleus}</version>
          </dependency>
        </dependencies>
      </plugin>
달리를 통한 이클립스의 JPA 2.0 지원("Eclipse IDE for JE Developers"에 포함)에는 Eclipse와 통합된 자체 메타모델 생성기가 있습니다.
- 패키지 탐색기에서 프로젝트를 선택합니다.
 - [ Properties ]-> [ JPA ]대화상자로 이동합니다.
 - Canonical 메타모델(JPA 2.0) 그룹에서 원본 폴더 선택
 - 선택한 소스 폴더에 메타모델 클래스를 생성하려면 적용 버튼을 클릭하십시오.
 

생성된 클래스가 표준이므로 이 기능은 모든 JPA 프로바이더에서 작동해야 합니다.
여기도 봐주세요.
하는 용어가 다음과  가정해 보겠습니다.Post,PostComment,PostDetails , , , , 입니다.Tag 대 다, 1 1 및 다 대 다 하는 엔티티: 1 대 다, 1 대 다 테이블 관계:
JPA Criteria 메타모델 생성 방법
hibernate-jpamodelgenHibernate ORM에서 제공하는 도구를 사용하여 프로젝트 엔티티를 스캔하고 JPA Criteria 메타모델을 생성할 수 있습니다. 해서 여러분이  할 은 다음과 같은 입니다.annotationProcessorPathmaven-compiler-pluginpom.xml★★★★★★★★★
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${maven-compiler-plugin.version}</version>
    <configuration>
        <annotationProcessorPaths>
            <annotationProcessorPath>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-jpamodelgen</artifactId>
                <version>${hibernate.version}</version>
            </annotationProcessorPath>
        </annotationProcessorPaths>
    </configuration>
</plugin>
 
.target자바어
> tree target/generated-sources/
target/generated-sources/
└── annotations
    └── com
        └── vladmihalcea
            └── book
                └── hpjp
                    └── hibernate
                        ├── forum
                        │   ├── PostComment_.java
                        │   ├── PostDetails_.java
                        │   ├── Post_.java
                        │   └── Tag_.java
 
태그 도면요소 메타모델
 경우,Tag엔티티는 다음과 같이 매핑됩니다.
@Entity
@Table(name = "tag")
public class Tag {
    @Id
    private Long id;
    private String name;
    //Getters and setters omitted for brevity
}
 
Tag_메타모델 클래스는 다음과 같이 생성됩니다.
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Tag.class)
public abstract class Tag_ {
    public static volatile SingularAttribute<Tag, String> name;
    public static volatile SingularAttribute<Tag, Long> id;
    public static final String NAME = "name";
    public static final String ID = "id";
}
 
SingularAttribute입니다.id ★★★★★★★★★★★★★★★★★」name TagJPA j j j j j j j j
포스트 엔티티 메타모델
Post엔티티는 다음과 같이 매핑됩니다.
@Entity
@Table(name = "post")
public class Post {
    @Id
    private Long id;
    private String title;
    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();
    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        fetch = FetchType.LAZY
    )
    @LazyToOne(LazyToOneOption.NO_PROXY)
    private PostDetails details;
    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(name = "post_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    private List<Tag> tags = new ArrayList<>();
    
    //Getters and setters omitted for brevity
}
 
Post에는 두  기본. 즉, 엔티티에는 두 가지 기본 속성이 있습니다.id ★★★★★★★★★★★★★★★★★」title 다, 1대 다, 1대 다comments,의 " ", "detailstags★★★★★★ 。
Post_메타모델 클래스는 다음과 같이 생성됩니다.
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Post.class)
public abstract class Post_ {
    public static volatile ListAttribute<Post, PostComment> comments;
    public static volatile SingularAttribute<Post, PostDetails> details;
    public static volatile SingularAttribute<Post, Long> id;
    public static volatile SingularAttribute<Post, String> title;
    public static volatile ListAttribute<Post, Tag> tags;
    public static final String COMMENTS = "comments";
    public static final String DETAILS = "details";
    public static final String ID = "id";
    public static final String TITLE = "title";
    public static final String TAGS = "tags";
}
 
 ★★id ★★★★★★★★★★★★★★★★★」title attributes, as well as the one-to-one Atribut과 1대 1의 어트리뷰트details association, are represented by a 어소시에이션, 에 의해 표시됩니다.SingularAttribute그 사?comments and 그리고.tags collections are represented by the JPA 컬렉션은 JPA에 의해 대표됩니다.ListAttribute....
PostDetails 엔티티 메타모델
그 thePostDetails이 같은 기업은 다음과 같은 매핑됩니다.엔티티는 다음과 같이 매핑됩니다.
@Entity
@Table(name = "post_details")
public class PostDetails {
    @Id
    @GeneratedValue
    private Long id;
    @Column(name = "created_on")
    private Date createdOn;
    @Column(name = "created_by")
    private String createdBy;
    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id")
    private Post post;
    
    //Getters and setters omitted for brevity
}
 
모든 기업은 JPA 티 성 티 은 시 해 됩 j다 all entity표니utes attrib to theed going의 are속 j엔 be represent by에papa든모SingularAttribute연관된 관.PostDetails_메타모델 클래스:메타모델 클래스:
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostDetails.class)
public abstract class PostDetails_ {
    public static volatile SingularAttribute<PostDetails, Post> post;
    public static volatile SingularAttribute<PostDetails, String> createdBy;
    public static volatile SingularAttribute<PostDetails, Long> id;
    public static volatile SingularAttribute<PostDetails, Date> createdOn;
    public static final String POST = "post";
    public static final String CREATED_BY = "createdBy";
    public static final String ID = "id";
    public static final String CREATED_ON = "createdOn";
}
 
PostComment 엔티티 메타모델
그 thePostComment is mapped as follows:는 다음과 같이 매핑됩니다.
@Entity
@Table(name = "post_comment")
public class PostComment {
    @Id
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;
    private String review;
    
    //Getters and setters omitted for brevity
}
 
그리고, 모든 기업은 JPA 든 성 티 은 j 시 해 표 됩 and니,다 entity의 attributes all theed속 are represent엔모 j티 by에papa한또SingularAttribute연관된 관.PostComments_메타모델 클래스:메타모델 클래스:
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostComment.class)
public abstract class PostComment_ {
    public static volatile SingularAttribute<PostComment, Post> post;
    public static volatile SingularAttribute<PostComment, String> review;
    public static volatile SingularAttribute<PostComment, Long> id;
    public static final String POST = "post";
    public static final String REVIEW = "review";
    public static final String ID = "id";
}
 
JPA Criteria 메타모델 사용
JPA 메타모델이 없으면 JPA 메타모델을 가져오려면 표준 API 쿼리를 가져와야 한다.PostComment entities filtered by their associated 연관된 엔티티로 필터링된 엔티티Post제목은 다음과 같습니다.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join("post");
query.where(
    builder.equal(
        post.get("title"),
        "High-Performance Java Persistence"
    )
);
List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();
 
다음 명령어를 사용한 것에 주의해 주세요.post작성 시 문자열 리터럴Joininstance를 사용하여title를 참조할 때의 문자열 리터럴Post title.
JPA Metamodel을 사용하면 다음 예시와 같이 엔티티 Atribut의 하드코딩을 피할 수 있습니다.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join(PostComment_.post);
query.where(
    builder.equal(
        post.get(Post_.title),
        "High-Performance Java Persistence"
    )
);
List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();
 
또는 DTO 투영을 가져오는 동안,Post title및 그PostDetails createdOn특성.
결합 애트리뷰트를 작성할 때, DTO 투영 컬럼에일리어스를 작성할 때 또는 필터링해야 하는 엔티티 애트리뷰트를 참조할 때 메타모델을 사용할 수 있습니다.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join(PostComment_.post);
query.multiselect(
    postComment.get(PostComment_.id).alias(PostComment_.ID),
    postComment.get(PostComment_.review).alias(PostComment_.REVIEW),
    post.get(Post_.title).alias(Post_.TITLE)
);
query.where(
    builder.and(
        builder.like(
            post.get(Post_.title),
            "%Java Persistence%"
        ),
        builder.equal(
            post.get(Post_.details).get(PostDetails_.CREATED_BY),
            "Vlad Mihalcea"
        )
    )
);
List<PostCommentSummary> comments = entityManager
    .createQuery(query)
    .unwrap(Query.class)
    .setResultTransformer(Transformers.aliasToBean(PostCommentSummary.class))
    .getResultList();
 
멋있죠?
eclipselink의 경우 메타모델을 생성하기에 충분한 종속성은 다음과 같습니다.다른 건 필요 없어요.
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.5.1</version>
        <scope>provided</scope>
    </dependency>
가장 일반적인 IMHO 프로바이더로서의 휴지 상태의 경우:
Gradle, Maven과 같은 빌드 툴의 경우 클래스 패스에 Hibernate JPA 2 Metamodel Generator jar가 필요하며 컴파일러 레벨 > = 1.6만 있으면 프로젝트를 빌드하면 자동으로 메타모델이 생성됩니다.
IDE Eclipse 1. goto Project -> Properties -> Java 컴파일러 -> Annotation Processing -> Annotation Processing (주석처리)을 펼쳐 활성화 합니다.2 . [ Factory Path - ]> [ Add External Jar add Hibernate JPA 2 Metamodel Generator jar ](JPA 2 메타모델 생성기 추가)의 jar를 체크하고 OK라고 합니다.깔끔하고 구축 완료!
maven repo https://mvnrepository.com/artifact/org.hibernate/hibernate-jpamodelgen에서 링크 휴지 상태 JPA 2 메타모델 생성기 jar 링크
네, 제가 읽은 것을 바탕으로, 저는 이 방법으로 프로세서 의존도를 해야 했고, 프로젝트에만 프로세서 종속성을 배치해야 할 필요가 없었습니다.annotationProcessorPath컴파일러 플러그인의 요소.
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <annotationProcessorPaths>
                <annotationProcessorPath>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.7.7</version>
                </annotationProcessorPath>
            </annotationProcessorPaths>
            <compilerArgs>
                <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
            </compilerArgs>
        </configuration>
    </plugin>
언급URL : https://stackoverflow.com/questions/3037593/how-to-generate-the-jpa-entity-metamodel
'programing' 카테고리의 다른 글
| PHPUnit - 구성 파일 사용 시 '테스트가 실행되지 않음' (0) | 2022.10.30 | 
|---|---|
| v-model이 null인 경우 Vue.js에서 확인란 값을 false로 설정합니다. (0) | 2022.10.30 | 
| Spring MVC(@Response Body)에서 응답 콘텐츠 유형을 설정하는 사용자 (0) | 2022.10.30 | 
| Python에서 변수와 문자열을 같은 줄에 인쇄하려면 어떻게 해야 하나요? (0) | 2022.10.30 | 
| Ajax 요청을 사용하여 파일 다운로드 (0) | 2022.10.30 | 
