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

总部:

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

}

4

1 回答 1

3

好吧,首先,您的查询太复杂了。可以改写为

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));
于 2012-11-25T15:22:54.950 回答