使用 Play 查找多对多实体交集的优雅方法
假设我有一个像这样使用 Play 框架的 Model 类实现的 Student 实体:
@Entity
public class Student extends Model {
public String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "student_subject",
joinColumns = {@JoinColumn(name = "student_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "subject_id", referencedColumnName = "id")})
public List<Subject> subjects;
...
}
主题如下所示:
@Entity
public class Subject extends Model {
public String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "student_subject",
joinColumns = {@JoinColumn(name = "subject_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "student_id", referencedColumnName = "id")})
public List<Student> students;
...
}
有没有一种使用 Play! 的简单方法? (如果不是,最好的方法是什么)找到与特定学生至少有一个共同点的所有学生?
假设:
- 学生 A 做数学、科学和英语
- 学生 B 做科学和英语
- 学生 C 做法语
- 学生 D 做数学和法语
我希望做一些像这样简单的事情:
List<Student> students = Student.find("subjects in ? and id <> ?", studentA.subjects, studentA.id).fetch();
我希望返回两个学生:B 和D(因为通过上述查询传入的学生 B 和 D 至少有一个与学生 A 相同的科目)。
Let's say I have a Student entity like this implemented using the Play Framework's Model class:
@Entity
public class Student extends Model {
public String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "student_subject",
joinColumns = {@JoinColumn(name = "student_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "subject_id", referencedColumnName = "id")})
public List<Subject> subjects;
...
}
And a Subject looks like this:
@Entity
public class Subject extends Model {
public String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "student_subject",
joinColumns = {@JoinColumn(name = "subject_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "student_id", referencedColumnName = "id")})
public List<Student> students;
...
}
Is there a simple way using Play! (if not, what is the best way to do it otherwise) to find all students that have at least one subject in common with a particular student?
So let's say:
- Student A does Maths, Science and English
- Student B does Science and English
- Student C does French
- Student D does Maths and French
I was hoping to do something as simple as this:
List<Student> students = Student.find("subjects in ? and id <> ?", studentA.subjects, studentA.id).fetch();
which I would expect to return two Students: B and D (since Students B and D have at least one subject in common with Student A as passed in via the query above).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我将使用的 JPQL 查询:
它与您的查询非常相似,但您需要一个联接才能在 where 子句中使用搜索到的学生的主题。
Here is the JPQL query I would use :
It's pretty similar to your query, but you need a join to be able to use the subjects of the searched students in the where clause.