尽管您得到了有效的结果,但 SQL 查询会获取所有数据,但效率并没有达到应有的水平。
所以,你有两个选择。
修复了两个可以在读写模式下获取实体的 SQL 查询的问题
解决此问题的最简单方法是执行两个查询:
. 第一个查询将获取与提供的过滤条件匹配的根实体标识符。. 第二个查询将使用先前提取的根实体标识符来获取父实体和子实体。
这种方法很容易实现,如下所示:
List<Long> postIds = entityManager
.createQuery(
"select p.id " +
"from Post p " +
"where p.title like :titlePattern " +
"order by p.createdOn", Long.class)
.setParameter(
"titlePattern",
"High-Performance Java Persistence %"
)
.setMaxResults(5)
.getResultList();
List<Post> posts = entityManager
.createQuery(
"select distinct p " +
"from Post p " +
"left join fetch p.comments " +
"where p.id in (:postIds) " +
"order by p.createdOn", Post.class)
.setParameter("postIds", postIds)
.setHint(
"hibernate.query.passDistinctThrough",
false
)
.getResultList();
修复了一个 SQL 查询只能在只读模式下获取实体的问题
第二种方法是对匹配我们过滤条件的父子实体的结果集使用 SDENSE_RANK,并仅限制前 N 个帖子条目的输出。
SQL 查询如下所示:
@NamedNativeQuery(
name = "PostWithCommentByRank",
query =
"SELECT * " +
"FROM ( " +
" SELECT *, dense_rank() OVER (ORDER BY \"p.created_on\", \"p.id\") rank " +
" FROM ( " +
" SELECT p.id AS \"p.id\", " +
" p.created_on AS \"p.created_on\", " +
" p.title AS \"p.title\", " +
" pc.id as \"pc.id\", " +
" pc.created_on AS \"pc.created_on\", " +
" pc.review AS \"pc.review\", " +
" pc.post_id AS \"pc.post_id\" " +
" FROM post p " +
" LEFT JOIN post_comment pc ON p.id = pc.post_id " +
" WHERE p.title LIKE :titlePattern " +
" ORDER BY p.created_on " +
" ) p_pc " +
") p_pc_r " +
"WHERE p_pc_r.rank <= :rank ",
resultSetMapping = "PostWithCommentByRankMapping"
)
@SqlResultSetMapping(
name = "PostWithCommentByRankMapping",
entities = {
@EntityResult(
entityClass = Post.class,
fields = {
@FieldResult(name = "id", column = "p.id"),
@FieldResult(name = "createdOn", column = "p.created_on"),
@FieldResult(name = "title", column = "p.title"),
}
),
@EntityResult(
entityClass = PostComment.class,
fields = {
@FieldResult(name = "id", column = "pc.id"),
@FieldResult(name = "createdOn", column = "pc.created_on"),
@FieldResult(name = "review", column = "pc.review"),
@FieldResult(name = "post", column = "pc.post_id"),
}
)
}
)
获取与提供的标题匹配的@NamedNativeQuery
所有 Post 实体及其关联的PostComment
子实体。DENSE_RANK
Window Function 用于为每个 Post 和 join 记录分配排名,以便PostComment
我们稍后可以过滤我们有兴趣获取的 Post 记录的数量。
SqlResultSetMapping
提供了 SQL 级别的列别名和需要填充的 JPA 实体属性之间的映射。
现在,我们可以PostWithCommentByRank
@NamedNativeQuery
这样执行:
List<Post> posts = entityManager
.createNamedQuery("PostWithCommentByRank")
.setParameter(
"titlePattern",
"High-Performance Java Persistence %"
)
.setParameter(
"rank",
5
)
.unwrap(NativeQuery.class)
.setResultTransformer(
new DistinctPostResultTransformer(entityManager)
)
.getResultList();
现在,默认情况下,像这样的原生 SQL 查询PostWithCommentByRank
会在同一 JDBC 行中获取 Post 和 the PostComment
,所以我们最终会得到一个Object[]
包含两个实体的。
但是,我们希望将表格Object[]
数组转换为父子实体树,因此,我们需要使用 Hibernate ResultTransformer
。
DistinctPostResultTransformer
外观如下:
public class DistinctPostResultTransformer
extends BasicTransformerAdapter {
private final EntityManager entityManager;
public DistinctPostResultTransformer(
EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public List transformList(
List list) {
Map<Serializable, Identifiable> identifiableMap =
new LinkedHashMap<>(list.size());
for (Object entityArray : list) {
if (Object[].class.isAssignableFrom(entityArray.getClass())) {
Post post = null;
PostComment comment = null;
Object[] tuples = (Object[]) entityArray;
for (Object tuple : tuples) {
if(tuple instanceof Identifiable) {
entityManager.detach(tuple);
if (tuple instanceof Post) {
post = (Post) tuple;
}
else if (tuple instanceof PostComment) {
comment = (PostComment) tuple;
}
else {
throw new UnsupportedOperationException(
"Tuple " + tuple.getClass() + " is not supported!"
);
}
}
}
if (post != null) {
if (!identifiableMap.containsKey(post.getId())) {
identifiableMap.put(post.getId(), post);
post.setComments(new ArrayList<>());
}
if (comment != null) {
post.addComment(comment);
}
}
}
}
return new ArrayList<>(identifiableMap.values());
}
}
必须分离正在获取的DistinctPostResultTransformer
实体,因为我们正在覆盖子集合,并且我们不希望它作为实体状态转换传播:
post.setComments(new ArrayList<>());