我目前正在尝试Hibernate Criteria。
考虑我有以下实体。
@Entity
@Table(name="form_table_name")
public class Forms extends Auditable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="FormID")
private Long formID;
@Column(name="FormTitle")
private String formTitle;
@OneToMany(mappedBy = "form", fetch = FetchType.EAGER , cascade = {CascadeType.ALL} , orphanRemoval = true)
private Set<FormsResponses> responses;
..........//rest of the code with fields, getters, setters etc.
@Entity
@Table(name="response_table_name")
public class FormsResponses extends Auditable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ResponseID")
private Long responseID;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="FormID")
private Forms form;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="OnBehalfOf")
private Users onBehalfOf;
..........//rest of the code
考虑我有以下数据 form_table_name
FormID FormTitle
------ ---------
1 Form1
2 Form2
response_table_name
ResponseID FormID OnBehalfOf
---------- ------ ----------
1 1 user1
2 1 user2
4 2 user2
我想加载来自 Forms 实体的数据,当且仅当 FormsResponses 中没有与我传递给&#39; onBehalfOf&的值相对应的记录时#39;字段和&#39; formID&#39;。
说,我现在的onBehalf&#39;价值是&#39; user1&#39;。我想检索form1和form2。但是,如果表单中包含“用户1”,则不应显示该表单。在其formsResponse映射行中。或者,如果用户已经尝试过表单,则不应该检索该表单。在这种情况下,表格将是&#39; Form2&#39;并且对于用户2&#39;它将是空的&#39;
Criteria cr = session.createCriteria(Forms.class);
cr.createCriteria("responses", "res", CriteriaSpecification.LEFT_JOIN)
.add(Restrictions.eq("res.onBehalfOf.userID", userID));
cr.add(Restrictions.sizeEq("responses", 0));
我试过这个,但它没有达到我的目的。我希望有人能指出我正确的方向。
答案 0 :(得分:0)
这是您的查询的样子:
Criteria c = session.createCriteria(Forms.class, "frm");
c.createAlias("frm.responses", "res", CriteriaSpecification.LEFT_JOIN);
c.createAlias("res.onBehalfOf", "beh", CriteriaSpecification.LEFT_JOIN, Restrictions.eq("beh.userID", userID));
c.add(Restrictions.isNull("beh.userID"));
return c.list();