简体   繁体   English

休眠中子对象列表的条件查询

[英]Criteria query on child object list in hibernate

I have an Entity class A with child class as pendingUsers like below. 我有一个带有子类的Entity类A,如下所示为pendingUsers。

A.java 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 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. 我想检索所有已将userId作为批准者之一的对象。 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. INNER_JOIN将仅返回具有批准者的记录,LEFT_OUTER_JOIN将返回所有具有批准者的父行(如果有)。

Use: org.hibernate.sql.JoinType 使用:org.hibernate.sql.JoinType

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM