繁体   English   中英

在 Mysql/Hibernate 中获取子实体

[英]Fetching child entities in Mysql/Hibernate

我使用 JPA 作为持久化引擎来处理数据库查询。 表(MySQL)如下:

Parent - table
+-----+---------+
|id   |   name  |
+-----+---------+
| 1   |  name1  |
| 2   |  name2  |
| 3   |  name3  |
+---------------+

child1 - table 
+--+---------+------+
|id|parent_id|name  |
+--+---------+------+
| 1|   1     |  qwe |
| 2|   1     |  asd | 
| 3|   1     |  dsf |
| 4|   2     |  xzc |
+--+---------+------+

child2 - table 
+--+---------+------+------+
|id|parent_id|type  |name  |
+--+---------+------+------+
| 1|   1     |  1   | qqq  |
| 2|   1     |  1   | www  |
| 3|   1     |  1   | eee  |
| 4|   1     |  2   | aaa  |
| 5|   1     |  2   | sss  |
| 6|   1     |  2   | ddd  |
| 7|   1     |  3   | zzz  |
| 8|   2     |  1   | xxx  |
+--+---------+------+------+

我的课是

@Entity
@Table(name = "parent")
public class Parent{
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private int id;

    @Column(name = "name")
    private String name;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent")
    private List<Child1> children1;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent")
    private List<Child2> children2;

}

@Entity
@Table(name = "child1")
public class Child1{
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private int id;

    @Column(name = "name")
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", nullable = false)
    private Parent parent;

}

@Entity
@Table(name = "child2")
public class Child2{
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "type")
    private int type;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", nullable = false)
    private Parent parent;

}

我想通过以下方式获取父实体和子实体(在java 对象中嵌入他们自己的List对象)。 我只想为每个父级获取具有最大id 的 child1 实体。

(对于给定的示例,parent(id:1) 的 child1(id:3) 和 parent(id:2) 的 child1(id:4))。

此外,我想为每种类型的 child2 获取具有最大id 的 child2。

(对于给定的示例,child2(id:3)(max of type:1), child2(id:6)(max of type:2), child2(id:7)(max of type:3) for parent( id:1) 和 child2(id:8)(max of type:1) for parent(id:2))

最后,Parent(id:1) 在 List children1 中有一个 Child1(id:3),在 List children2 中有三个 Child2(id:3, id:6, id:7)。

对不起,我的英语不好。

谢谢你的帮助。

您真的应该发布到目前为止您尝试过的内容,但由于我还不能评论 Everywhere™,我将帮助您完成第一个,您可以自己尝试第二个。

我假设您要求 HQL 执行您的查询。 尝试这个:

select max(c.id), c.parent.id from Child1 c group by child1.parent.id

您想要的第二个查询非常相似,如果您可以使用该查询,那么它应该很容易。

我认为您想过滤子集合。 查看休眠过滤器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM