我有以下ManyToMany映射。@ManyToMany JPA 2複雜查詢
@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;
}
我想檢索所有Class1的實體,有關係有Classe2實體,與class2Id = 1和class2Id = 2和class2Id = 3。 {1,2,3}
或者篩選那些對他們的等級2列出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具有與relaion classe2Id:1,2,3,4 及1級實體,與class1Id = 2與classe2Id有關聯:1,2,3
是否有可能使用JPA2(Predicate)返回正確的實體?
有沒有更好的映射來處理這種情況?
就目前而言,我想出了下面的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;
你能澄清你的問題/例子嗎? – HRgiger 2012-08-09 21:50:15
我已經添加了更多說明 – brianbro 2012-08-09 22:29:30