【发布时间】:2012-08-07 04:52:43
【问题描述】:
我有以下多对多映射。
@Entity
public class Class1 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "class1_class2", joinColumns = @JoinColumn(name = "class1Id"), inverseJoinColumns = @JoinColumn(name = "class2Id"))
private List<Class2> class2;
}
@Entity
public class Class2 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
}
我想检索与 Classe2 实体有关系的所有 Class1 实体,其中 class2Id = 1 和 class2Id =2 和 class2Id =3。 {1,2,3}
或者过滤 Class2 列表中的 Classe1 实体,Class2 实体的值为:class2Id = 1 和 class2Id =2 和 class2Id =3
例如:
如果在连接表上,我有以下值。
class1Id class2Id
1 1
1 2
1 3
1 4
6 1
6 2
6 3
4 1
5 2
对于本示例,结果将是 Class1 和 class1Id:1 和 6。 因为 Class1 实体,class1Id=1 与 classe2Id 有关系:1,2,3,4 而 Class1 实体,class1Id=2 与 classe2Id: 1,2,3 有关系
是否可以通过 JPA2(谓词)返回正确的实体?
有没有更好的映射来处理这种情况?
目前,我想出了以下 SQL 查询:
select v1.class1Id from class1_class2 v1
inner join class1_class2 v2 on v1.class1Id=v2.class1Id
inner join class1_class2 v3 on v2.class1Id=v3.class1Id
where v1.classe2Id=1 and v2.classe2Id=2 and v3.classe2Id=3;
【问题讨论】:
-
你能澄清你的问题/例子吗?
-
我已经添加了更多说明
标签: java hibernate jpa jpa-2.0 spring-data-jpa