Home How to query for entities by their object collection value in JPA criteria api
Reply: 1

How to query for entities by their object collection value in JPA criteria api

Chidambar Shiragalle
1#
Chidambar Shiragalle Published in 2018-02-12 16:37:09Z

I am using JPA with JSF datatable with lazy loading. Here One car can be owned by many users. So when i logged in to the application i want the cars which is owned by the user logged in(assume it as userId=1). I have a mapping table "Cars_User" that contains carId and userId columns. My Entities are like this My Car Class

@Entity
@Table(name="car")
public class Car implements Serializable {
 private static final long serialVersionUID = 1L;

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

 @Transient
 private boolean myCar;

 @NotNull
 @Size(min = 1, max = 50)
 public String name;

 @OneToMany(cascade = { CascadeType.REFRESH }, fetch = FetchType.LAZY, orphanRemoval = true)
 @JoinTable(name = "Cars_User", joinColumns = @JoinColumn(name = "carId"), inverseJoinColumns = @JoinColumn(name = "userId"))
 private List<User> carUsers = new ArrayList<User>();

 getters ...

 setters ...
}

User Class

@Entity(name = "User")
public class User implements Serializable {

   private static final long serialVersionUID = 1L;

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

   private String firstName;

   private String lastName;
}

I have found one answer for Lists of String collection in this link but how can be achieved in my case. I wanted to do get all Cars entities in criteria api that contains the logged in user id "userId" in carUsers Lists. can anyone please help?

Chidambar Shiragalle
2#
Chidambar Shiragalle Reply to 2018-02-13 19:55:49Z

I found the solution. I have passed the logged in user Object "user" in isMember function. This may help for somebody.

CriteriaBuilder criteriaBuilder = em.getEntityManagerFactory().getCriteriaBuilder(); 
CriteriaQuery<Car> criteria = criteriaBuilder.createQuery(Car.class);
Root<Car> root = criteria.from(Car.class);
criteria.where(criteriaBuilder.isMember(user, root.get(Car_.carUsers)));
List<Car> cars = em.createQuery(criteria).getResultList();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.310538 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO