[英]JPA/Hibernate SELECT all parent fields with Child count in Single Query
[英]select parent and count of all child class in JPA
我有以下JPA实体结构。
@Entity
@Table(name = "PARENT_DETAILS")
class Parent{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "parent_details_seq")
@SequenceGenerator(name = "parent_details_seq", sequenceName = "PARENT_DETAILS_SEQ", allocationSize = 1)
@Column(name = "PARENT_ID")
private long parentId;
@Column(name = "PARENT_NAME")
private String parentName;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "childPK.parent", cascade = CascadeType.ALL)
private Set<Child> child;
//setters and getters
}
@Entity
@Table(name = "CHILD_DETAILS")
public class Child {
private ChildPK childPK;
public void setProgramProcessesPK(ChildPK childPK) {
this.childPK = childPK;
}
@EmbeddedId
public ChildPK getChildPK() {
return childPK;
}
}
@Embeddable
public class ChildPK implements Serializable {
private static final long serialVersionUID = 1L;
private Parent parent;
private long childId;
@Column(name = "CHILDID")
public long getChildId() {
return childId;
}
public void setChildId(long childId) {
this.childId = childId;
}
@ManyToOne
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", nullable = false)
public ParentDetails getParent() {
return parent;
}
}
我想编写一个JPA查询,该查询将返回PARENT_NAME和给定parent_id的所有子项的计数。
我能想到的唯一解决方案是加入并编写一个复杂的条件查询。
我想不出一种使用简单的JPA查询获得结果的方法。
有没有更简单的方法可以做到这一点?
您尝试过SIZE吗? 诸如“从父级父母中选择parent.parentName,Size(parent.child)”之类的方法可能适用。
您可以使用诸如以下的“ JPA命名查询”:
private static class ParentChildsNumber {
public String parentName;
public Integer childsNum;
public ParentChildsNumber(String parentName, Integer childsNum) {
this.parentName = parentName;
this.childsNum = childsNum;
}
}
@NamedQuery(name="getParentChildsNumberQuery", query="SELECT NEW ParentChildsNumber(p.parentName, SIZE(p.child)) FROM Parent p WHERE p.parentId = :parentId GROUP BY p.parentId, p.parentName")
通过以下方式在代码中使用它:
@PersistenceContext(unitName="YourPersistentUnit")
private EntityManager em;
em.createNamedQuery("getParentChildsNumberQuery", ParentChildsNumber.class).setParameter("parentId", parentId).getSingleResult();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.