I have an Entity class A with child class as pendingUsers like below.
A.java
@Entity
public class A implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "PENDING", joinColumns = {@JoinColumn(name = "aId")}, inverseJoinColumns = {@JoinColumn(name = "userId")})
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Set<User> approvers = new HashSet<User>();
@Column(name = "active", nullable = false, columnDefinition = "varchar default 'Y'")
@org.hibernate.annotations.Type(type = "yes_no")
private boolean active = true;
@NotBlank
@Column(nullable = false, unique = true)
private String poNo;
}
User.java
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@NotBlank(message = "User ID cannot be empty")
@Column(unique = true, nullable = false, updatable = false)
private String userId;
}
I want to retrieve all A objects which has given userId as one of the approver. How to write this with hibernate Criteria?
I wrote like below when I had one to one mapping.
createEntityCriteria()
.add(Restrictions.eq("approvers.userId", userId))
.add(Restrictions.eq("active", true)).list();
As we changed now to many to many mapping how to achieve this?
I am quite new to this, however I've used this method successfully with many entities in a project that I am working on.
I've had this functionality working with code similar to what you have mentioned above. However, in case that does not work, you can play around with a Join, as follows:
createEntityCriteria()
.createAlias("approvers", "apprs", JoinType.INNER_JOIN)
.add(Restrictions.eq("apprs.userId", userId))
.add(Restrictions.eq("active", true)).list();
INNER_JOIN will return only records that have an approver, LEFT_OUTER_JOIN will return all parent rows with the approver where available.
Use: org.hibernate.sql.JoinType
Hope this helps.
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.