【问题标题】:SqlResultSetMapping native SQL query and One2Many relationsSqlResultSetMapping 原生 SQL 查询和 One2Many 关系
【发布时间】:2015-05-30 20:34:36
【问题描述】:

是否有可能在SqlResultSetMappingentityManager.createNativeQuery 的帮助下从两个不同的表中获取具有One2Many 关系的对象?

例如

@Entity
@Table(name = "posts")
public class Post {
    @OneToMany(mappedBy = "post")
    private List<Comment> comments;
}

@Entity
@Table(name = "comments")
public class Comment {
    @ManyToOne(optional = false)
    @JoinColumn(name = "post_id", referencedColumnName = "post_id")
    private Post post;
}

查询:

select p.*, c.* from posts p left join (
    select * from comments where content like "%test%" order by last_edited limit 0, 3) 
as c on p.post_id = c.post_id

基于 native sql 查询,我需要使用 cmets 获取帖子对象。

我的意思是 - 因此我需要接收帖子列表,并且此列表中的每个帖子都已经填充了适当的评论。

JPA 可以吗?如果是这样,你能举个例子吗?

【问题讨论】:

    标签: mysql hibernate jpa hql jpql


    【解决方案1】:

    你可以这样做:

    SELECT post from Post post 
    LEFT JOIN FETCH post.comments -- to fetch all comments in each post
    LEFT JOIN FETCH post.comments comment -- to do the WHERE
    WHERE comment.content like "%test%"
    

    问题是order by last_edited。我认为您无法在 JPA 中对获取的 cmets 列表进行排序,但您可以将此注释放在 private List&lt;Comment&gt; comments; 中以在集合中设置默认顺序:

    @OneToMany(mappedBy = "post")
    @OrderBy("lastEdited asc")
    private List<Comment> comments;
    

    最后,对于limit,使用方法firstResultmaxResults from JPA

    return em.createQuery(query)
             .setFirstResult(0) // offset
             .setMaxResults(3) // limit
             .getResultList();
    

    【讨论】:

      猜你喜欢
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 2015-04-09
      • 2014-01-12
      • 2016-10-11
      • 2011-08-28
      • 2012-06-18
      相关资源
      最近更新 更多