我有以下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查询获取结果的方法。
有更简单的方法吗?
答案 0 :(得分:0)
你试过SIZE吗?像“从父父中选择parent.parentName,Size(parent.child)”这样的东西可能会起作用。
答案 1 :(得分:0)
您可以使用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();