Come scrivere query con una colonna di conteggio aggiuntiva utilizzando JPA Criteria Builder

Aug 18 2020

Sto lottando per scrivere una query JPA che restituisca tutti gli oggetti P che si trovano nel database e accanto a loro voglio avere il conteggio dei loro figli S che hanno propertyA = 1.

Query SQL

Seleziona p. *, (Seleziona count (s.id) da s_table s WHERE p.id = s.p_id e s.propertyA = 1) da p_table p

La mappatura:

@Entity
@Table(name = "t_table")
public class PTable{
    @Id
    private String id;

    @Version
    private Long version;

    private String subject;
   
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    @JoinColumn(name = "p_id", referencedColumnName = "id")
    private Set<STable> sSet = new HashSet<>();
}
 
@Entity
@Table(name = "s_table")
public class STable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "p_id")
    private String pId;
  
    private String propertyA;
}

Inoltre, ti piacerebbe indicare qualsiasi buon tutorial per scrivere query complesse in JPA.

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<PTable> q = cb.createQuery(PTable.class);
Root<PTable> c = q.from(PTable.class);

Risposte

JLazar0 Aug 19 2020 at 09:57
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyPojo> cq = cb.createQuery(MyPojo.class);

Root<PTable> rootPTable = cq.from(PTable.class);
Join<PTable, STable> joinSTable = rootPTable.join(PTable_.sSet);

Subquery<Long> sqCount = cq.subquery(Long.class);
Root<STable> sqRootSTable = sqCount.from(STable.class);
Join<STable, PTable> sqJoinPTable = sqRootSTable.join(STable_.pSet);

sqCount.where(cb.and(
    cb.equal(sqJoinPTable.get(PTable_.id),rootPTable.get(PTable_.id)),
    cb.equal(sqRootSTable.get(STable_.propertyA),"1")));

sqCount.select(cb.count(sqRootSTable));

cq.multiselect(
    rootPTable.get(PTable_.id),
    rootPTable.get(PTable_.version),
    rootPTable.get(PTable_.subject),
    joinSTable.get(STable_.id),
    sqCount.getSelection(),
);

Avrai bisogno di un Pojo per ottenere i risultati che un costruttore ha che corrisponde in ordine e digita con i parametri multiselect come segue:

public MyPojo(String pId, Long version, String subject, Long sId, Long count){
    [...]
}

Dovrai anche modificare le tue entità per mappare correttamente la relazione, essendo bidirezionale e pigro per migliorare le prestazioni come segue:

PTable

@OneToMany(mappedBy="p",fetch = FetchType.LAZY)
private Set<STable> sSet;

Stabile

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="id")
private PTable p;