JPA 2 criteria API: How to select values from various joined tables without using Metamodel?

喜夏-厌秋 提交于 2019-12-11 04:45:20

问题


I have the following type of query that I wish to convert into a jpa criteria query and the following table structure:

Table A 1-->1 Table B  1<--* Table C (proceedings) *-->1 Table D(prcoeedingsstatus)
--------      --------       -------                     -------
 aID           bID           cID                         dID
 ...           ....          timestamp                   textValue
 f_bID         ....          f_bID       
                             f_dID

1 A has 1 B, 1 B has many proceedings and each proceeding has a proceedingstatus.

SELECT a.*

FROM ((a LEFT JOIN b ON a.f_b = b.id)
        LEFT JOIN proceedings ON b.id = proceedings.f_b)
        RIGHT JOIN proceedingsstatus ON proceedings.f_d = proceedingsstatus.id

WHERE   d.textValue IN ("some unique text")
        AND c.timestamp BETWEEN 'somedate' AND 'anotherdate'

When I now try to do something like this for the predicates:

Predicate conditions = (root.join("tableB")
                            .joinList("proceedings")
                            .join("proceedingsstatus").get("textValue"))
                            .in(constraintList.getSelectedValues());

Predicate time = cb.between((root.join("tableB")
                            .joinList("proceedings")
                            .<Date>get("timestamp")), dt1.toDate(), dt2.toDate());

constraints = cb.and(conditions, time);

Right now it selects entries A where there is at least 1 occurrence of the right proceedingsstatus according to the conditions-predicate if in any of A's proceedings the 'timestamp' matches the time-predicate that I built. So it would also select an entry A when C.timestamp is correct for a proceeding with the wrong textValue in D, if there is at least one entry C belonging to A with the right textvalue in D.

How can I change it so that it only selects A's where the proceedingsstatus has the right value AND the time of proceeds is correct?


回答1:


Reuse the joins instead of creating new ones for each predicate.

Join proceedings = root.join("tableB").joinList("proceedings");


来源:https://stackoverflow.com/questions/13270857/jpa-2-criteria-api-how-to-select-values-from-various-joined-tables-without-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!