簡體   English   中英

在JPA中選擇父級並計數所有子級

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM