简体   繁体   中英

JPA Criteria API - LEFT OUTER JOIN not populating a @OneToMany List

This is my entity:

public class Patrimony {

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

    @OneToMany(mappedBy = "patrimony")
    @JsonManagedReference 
    private
    List<Patrpos> positions;
}

My code is:

CriteriaBuilder cb = manager.getCriteriaBuilder();

CriteriaQuery<Patrimony> cq = cb.createQuery(Patrimony.class);
Root<Patrimony> root = cq.from(Patrimony.class);

Join<Patrimony, UserProfile> userprofile = root.join(Patrimony_.userprofile);
Join<Patrimony, Patrpos> joinPatrpos = root.join(Patrimony_.positions, JoinType.LEFT);
root.fetch(Patrimony_.positions);

joinPatrpos.on(cb.equal(joinPatrpos.get(Patrpos_.dtPatrpos), dateproc.minusDays(1)));

cq.select(root);

TypedQuery<Patrimony> query = manager.createQuery(cq);

List<Patrimony> list = query.getResultList();

The query that is being generated looks ok, and it's something like:

select
    patrimony0_.id as id1_10_0_,
    positions3_.id as id1_11_1_,
    patrimony0_.category_id as categor15_10_0_,
    patrimony0_.description as descript2_10_0_,
    patrimony0_.vl_valuation_start as vl_valu14_10_0_,
    positions3_.dt_patrpos as dt_patrp2_11_1_,
    positions3_.vl_patrpos as vl_patrp6_11_1_,
from
    patrimony patrimony0_ 
inner join
    userprofile userprofil1_ 
        on patrimony0_.userprofile_id=userprofil1_.id 
left outer join
    patrpos positions2_ 
        on patrimony0_.id=positions2_.patrimony_id 
        and (
            positions2_.dt_patrpos=?
        ) 
inner join
    patrpos positions3_ 
        on patrimony0_.id=positions3_.patrimony_id 
where userprofil1_.id=161

The query seems to be returning all the data that I need, the entity Patrimony is being returned with all the data ok, except the "List positions" attribute, which is always null.

Thank you.

Reviewing the unit test, I notice that I didn't call flush() and clear() after inserting the test data. I added flush and clear before calling the query and all the entities were populated correctly.

Thank you all for the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM