gpt4 book ai didi

java - hibernate 多对多加入条件

转载 作者:搜寻专家 更新时间:2023-11-01 01:36:09 26 4
gpt4 key购买 nike

+-------+    +--------------|     +-------+
| BOY | | BOY_GIRL | | GIRL |
+-------+ +--------------| +-------+
| id | | id | | id |
| name | | boy_id | | name |
| birth | | girl_id | | birth |
+-------+ | start_dating | +-------+
+--------------|

START_DATINGTIMESTAMPDATE 的类型>

我有两个具有多对多关系的 bean Boy 和 Girl

@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)

最佳答案

我认为你必须创建一个 BoyGirl 类,因为表 BOY_GIRL 不是一个简单的多对多表(如果是,那么列必须仅为 boy_idgirl_id)。所以你应该做的是创建 BoyGirl 类,然后将 BOY 一对多映射到 BOY_GIRL 并映射 GIRLBOY_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;
}

关于java - hibernate 多对多加入条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13153592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com