Search code examples
hibernatecriteriahibernate-criteria

How to convert this criteria code into CriteriaBuilder


I was setting up hibernate code using 3 Tables where I need to use entity class to fetch data rather using any query.

I have criteria code where I am using createAlias but not able to convert to CriteriaBuilder as criteria in hibernate is deprecated.

Criteria criteria = session.createCriteria(Star.class, "star"); 
criteria.createAlias("star.assignedTo", "assigned"); 
criteria.createAlias("assigned.team", "team"); 
criteria.add(Restrictions.eq("team.team_id", "12393")); 

I want to get this code into CriteriaBuilder.


Solution

  • Something like

    CriteriaBuilder cb; // if I remember correctly en can be obrained either from EntityManager or from CriteriaQuery - its been a while
    
    root=cb.from(Star.class);
    teamJoin=root.join("assignedTo").join("team");
    
    cb.eq(teamJoin.get("team_id"),yourid)) // thats the predicate
    

    obviously this is kind of pseudocode as I have no idea about your classes nor parth properties, but you should get the idea from here.

    Just remember that those joins are INNER JOINS. Every join can have specified type as second arg - just in case.