これは非常に一般的な質問であるため、この回答に基づいてこの記事を書きました。
私たちのアプリケーションは、以下の使用を前提としましょうPost、PostComment、PostDetails、およびTag1対多を形成するエンティティ、1対1、および多対多のテーブルのリレーションを:

JPA基準メタモデルを生成する方法
hibernate-jpamodelgenHibernateはORMが提供するツールは、プロジェクトのエンティティをスキャンし、JPA基準メタモデルを生成するために使用することができます。Maven 構成ファイルのに以下annotationProcessorPathを追加するだけです。maven-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フォルダー内に次のJavaクラスが生成されていることがわかります。
> 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エンティティ属性。
エンティティメタモデルの投稿
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エンティティは、2つの基本的な属性を持ち、idかつtitle、1対多のcommentsコレクション、1対1 detailsの関連、および多対多tagsのコレクションを。
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属性、および1対1のdetails関連付けはaで表されSingularAttribute、commentsおよびtagsコレクションはJPAで表されListAttributeます。
PostDetailsエンティティメタモデル
PostDetailsエンティティは次のようにマッピングされます。
@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
}
すべてのエンティティー属性はSingularAttribute、関連するPostDetails_MetamodelクラスのJPAによって表されます。
@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エンティティメタモデル
PostComment次のようにマップされます。
@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
}
また、すべてのエンティティー属性はSingularAttribute、関連するPostComments_MetamodelクラスのJPAによって表されます。
@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基準メタモデルの使用
JPAメタモデルがない場合、PostComment関連するPostタイトルでフィルタリングされたエンティティをフェッチする必要があるCriteria APIクエリは次のようになります。
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作成するときに文字列リテラルJoinを使用し、をtitle参照するときに文字列リテラルを使用したことに注意してくださいPost title。
JPAメタモデルを使用すると、次の例に示すように、エンティティ属性のハードコーディングを回避できます。
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();
Codotaのようなコード補完ツールを使用している場合、JPA基準APIクエリの記述ははるかに簡単です。チェックアウトこの記事を Codota IDEプラグインの詳細については。
または、フィルター処理中に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();
かっこいいですよね?