2012-11-25 369 views
2

我已經創建了下面提到的SQL的HQL,但我無法通過Criteria和Sub查詢來執行它。請幫助我通過Criteria執行以下查詢(SQL & HQL)。感謝提前 ...標準查詢多對多

SQL:

SELECT * FROM app_interface ain WHERE ain.id IN (SELECT ai.id FROM app_interface ai INNER JOIN app_module_interface ami ON ami.interface_id = ai.id INNER JOIN app_module am ON am.id = ami.module_id WHERE am.id = :id 

HQL:

FROM AppModule oam WHERE oam.id IN(SELECT am.id FROM AppModule am INNER JOIN am.appRoles ar WHERE ar.id = :id) 

通過所需的標準... .. ?????

場景:

public class AppModule implements java.io.Serializable { 
@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column(name = "id", unique = true, nullable = false) 
private Integer id; 

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "appModules") 
private Set<AppRole> appRoles = new HashSet<AppRole>(0); 

}

公共類AppRole實現java.io.Serializable {

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column(name = "id", unique = true, nullable = false) 
private Integer id; 

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) 
@OrderBy("name") 
@JoinTable(name = "app_role_module", joinColumns = { 
@JoinColumn(name = "role_id", nullable = false, updatable = false)}, inverseJoinColumns = { 
    @JoinColumn(name = "module_id", nullable = false, updatable = false)}) 
private Set<AppModule> appModules = new HashSet<AppModule>(0); 

}

回答

2

嗯,首先,你的查詢太複雜。它可以被改寫爲

select distinct am from AppModule am 
inner join am.appRoles ar 
WHERE ar.id = :id 

我不知道爲什麼你要使用的標準,而不是這種簡單易讀的HQL查詢,但如果你真的想要,然後用

Criteria c = session.createCriteria(AppModule.class, "am"); 
c.createAlias("am.appRoles", "ar"); 
c.add(Restrictions.eq("ar.id", theRoleId)); 
c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 

編輯:

如果你想實現查詢

from AppModule oam WHERE oam.id not in (
    select am.id from AppModule am inner am.appRoles ar where ar.id = :id) 

,那麼你可以使用下面的代碼:

DetachedCriteria dc = DetachedCriteria.forClass(AppModule.class, "am"); 
dc.createAlias("am.appRoles", "ar"); 
dc.add(Restrictions.eq("ar.id", theRoleId)); 
dc.setProjection(Projections.id()); 

Criteria c = session.createCriteria(AppModule.class, "oam"); 
c.add(SubQueries.propertyNotIn("oam.id", dc)); 
+0

我是新來的Hibernate,但不是太新:)。但任何如何......謝謝 –

+0

這個答案是關於IN運算符。但我也要求'FROM AppModule oam WHERE oam.id NOT IN(SELECT AM.ID FROM AppModule am IN JOIN IN am.appRoles ar WHERE ar.id =:id)' –

+0

請參閱我編輯的答案。 –