[英]Hibernate many-to-many join with condition
+-------+ +--------------| +-------+
| BOY | | BOY_GIRL | | GIRL |
+-------+ +--------------| +-------+
| id | | id | | id |
| name | | boy_id | | name |
| birth | | girl_id | | birth |
+-------+ | start_dating | +-------+
+--------------|
START_DATING
是TIMESTAMP
或DATE
類型
我有兩個豆子男孩和女孩有多對多的關系
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "BOY_GIRL", joinColumns = {@JoinColumn(name = "BOY_ID")}, inverseJoinColumns = {@JoinColumn(name = "GIRL_ID")})
public Set<Girl> getGirls() {
return girls;
}
現在,我如何使用HQL選擇查詢,如果我想獲得有條件的列表女孩:
where boy_id = (some_boy_id) and START_DATING > (some_timestamp)
我認為你的實體模型不正確,你需要一個代表關系屬性的第三個實體,你應該將男孩和女孩同時映射到該實體。 否則,無法在您的情況下將starting_date指定為關系屬性,作為查詢中的條件。 查看此鏈接 ,您可以找到有關如何使用其他屬性映射連接表的詳細說明。
我認為你必須創建一個BoyGirl
類,因為表BOY_GIRL
不是一個簡單的多對多表(如果是,那么列必須只是boy_id
和girl_id
)。 那么你應該做的是創建BoyGirl
類然后用BoyGirl
映射BOY
到BOY_GIRL
,並用一對多映射GIRL
到BOY_GIRL
表關系
+-------+ +--------------+ +-------+
| BOY | | BOY_GIRL | | GIRL |
+-------+ +--------------| +-------+
| id | 0..* --- 1..1 | id | 1..1 --- 0..* | id |
| name | | boy_id | | name |
| birth | | girl_id | | birth |
+-------+ | start_dating | +-------+
+--------------+
java類
public class BoyGirl {
private long id;
private Boy boy;
private Girl girl;
private Date startDating;
}
public class Boy {
//other attributes omitted
private Set<BoyGirl> boyGirls;
}
public class Girl {
//other attributes omitted
private Set<BoyGirl> boyGirls;
}
您需要的選擇查詢
// I'm using criteria here, but it will have the same result as your HQL
public List getGirls(Boy boy, Date startDating) {
Criteria c = sessionFactory.getCurrentSession().createCriteria(BoyGirl.class);
c.add(Restrictions.eq("boy.id", boy.getId());
c.add(Restrictions.lt("startDating", startDating);
List<BoyGirl> boyGirls = (List<BoyGirl>) c.list();
// at this point you have lazily fetch girl attributes
// if you need the girl attributes to be initialized uncomment line below
// for (BoyGirl boyGirl : boyGirls) Hibernate.initialize(boyGirl.getGirl());
return boyGirls;
}
由於中間表BOY_GIRL
具有一些額外的屬性( start_dating
),您需要在域模型中為它創建另一個中間實體,例如:
@Table(name="BOY_GIRL")
class Relationship {
@Id
long id;
@ManyToOne
Boy boy;
@ManyToOne;
Girl girl;
@Column
Date startDating;
}
我認為將約會信息直接保存在聯接表中並不是很好(因為這樣做的目的應該只是關聯一個男孩和一個女孩)。
但是,如果你真的想保留當前的結構,並用HQL解決它,你應該能夠做類似的事情
SELECT g FROM GIRL g, BOY_GIRL bg
WHERE bg.start_dating = :revelantdate
AND bg.boy_id = :boyid
AND g.id = bg.girl_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.