0

This is the query I want to rewrite using criteria query:

Query query = entityManager.createQuery( "Select a from UserDetails a where a.user.id = ?1")

How can I achieve this? I know how to do select with criteria query when I know some of the property of the entity I'm looking for but in this case I want to do select using foreign key. I got two entities:

@Entity
@Table(name = "user")
public class User {
    private String name;
    @OneToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.LAZY)
    private UserDetails userdetails;
etc.
 }

@Entity
@Table( name = "userdetails")
public class UserDetails
{
   @OneToOne( cascade = { CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.LAZY)
   @JoinColumn( name = "fk_user_id")
   private User user;
etc.
    }

I only know the id of the user and now I want to do select in userdetails with this user id. How can I do it?

TheBezwet
  • 33
  • 1
  • 10

1 Answers1

0

I have solved it this way:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<UserDetails > cq = cb.createQuery( UserDetails .class);
Root<UserDetails > root = cq.from( UserDetails .class);
cq.select(root);
cq.where(cb.equal( root.get("user").get("id"), userID));
return entityManager.createQuery(cq).getSingleResult;
TheBezwet
  • 33
  • 1
  • 10