JPA Criteria and Predicate on a EmbeddedId

4.3k views Asked by At

I have a little trouble. I am using JPA Criteria to make a dynamic select (using criteria as the the where clause has optional variable...) but one of my entity has a EmbeddedId that contains the user column of which and need to check the user id...

here are my Entities.

@Entity
@Table(name = "user_like") 
public class UserLike extends AbstractTimestampEntity implements Serializable {

  @EmbeddedId
   private UserLike.userLikePK userLikePK= new UserLike.UserLikePK();
   ...
   with all the setter and gets
   ...

   @Embeddable
   public static class UserLike implements Serializable{
      @ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
      @JoinColumn(name = "user_id")
      private User user;

      ... (and an other column, not important for now=
   }   
}

User is an other Entity that contains the column userId

Now this is what my query looks like.

Root<Poi> p = cq.from(Poi.class);
Join<Poi,UserLike> ul = p.join("userLike");


 List<Predicate> predicates = new ArrayList<Predicate>();
 Predicate predicate = cb.like(cb.upper(p.<String>get("name")), "%" + poiName.toUpperCase() + "%");
 predicates.add(predicate);

 Predicate predicate2 = cb.equal(ul.get("userLikePK.user.idUser"), userId);
 predicates.add(predicate);

 //multi select because i need some info from p and ul as well....
 cq.multiselect(p, ul);

Now the predicate2 obviously throw me an error "Unable to locate Attribute with the the given name [userPoiLikePK.user.idUser]"

Can someone tell me how can add my "equal" predicate on the userID ?

ps: this is the pa query i want to archive:

SELECT p,ul FROM Poi p LEFT JOIN p.userLike ul WHERE p.name like :name AND ul.user.idUser=:userId

Thank you!!

1

There are 1 answers

0
Alexis On BEST ANSWER

You need to chain the get.

Predicate predicate2 = cb.equal(ul.get("userLike").get("user").get("idUser"), userId);