Hibernate Criteria条件或OneToMany属性值上的子查询

我的应用程序的一个组件记录用户使用http URL发送的参数。 映射如下:

public class ActivityLog {

    @Column(name = "id")
    private Long id;

    @OneToMany(mappedBy="activityLog", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    protected List<ActivityLogParameter> activityLogParameters = new ArrayList<ActivityLogParameter>();
}

public class ActivityLogParameter {

    @Column(name = "id")
    private Long id;

    @Column(name = "key", length=10)
    protected String key;

    @Column(name = "value", length=50)
    protected String value;

    @ManyToOne(fetch = FetchType.LAZY, cascade={CascadeType.MERGE})
    @JoinColumn(name="activity_log_id")
    protected ActivityLog activityLog;
}

假设每个URL总是有2个参数被传递:U和L.

我需要使用hibernate的Criteria(规范中必须的)创建一个查询,以便它返回两个参数匹配一个特定值的所有ActivityLogs。 即:U = aaa和L = bbb

我试过这样的:

Criteria criteria = getCurrentSession().createCriteria(ActivityLog.class, "al");
// create alias
criteria = criteria.createAlias("activityLogParameters", "alp",JoinFragment.LEFT_OUTER_JOIN);

// create transformer to avoid duplicate results
criteria = criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
criteria = criteria.setFetchMode("al.activityLogParameters", FetchMode.SELECT);

//filters
criteria = criteria.add(Restrictions.or(Restrictions.eq("alp.value", UValue), Restrictions.ne("alp.key", "L")));
criteria = criteria.add(Restrictions.or(Restrictions.eq("alp.value", LValue), Restrictions.ne("alp.key", "U")));

但在这里,我卡住了。 我试图在这方面添加像独特和分组这样的投影,但仅仅得到正确的结果是不够的。

我也试图使用这个标准作为子标准,因此要计算任何ActivityLog的行数并只保留count(*)= 2(所有参数都符合条件)的记录,但我找不到如何使用子查询来完成。

任何想法如何解决上述问题? 在SQL中,我会做这样的事情:

select activity_log_id from (
    select count(*) as ct, activity_log_id 
    from activity_log_parameter alp inner join activity_log al on alp.activity_log_id=al.id 
    where (alp.value='visitor' or alp.key<>'U') 
        and (alp.value='room1' or alp.key<>'L') 
    group by activity_log_id
) as subq
where subq.ct = 2

谢谢


使用子查询解决

DetachedCriteria subquery = DetachedCriteria.forClass(ActivityLogParameter.class, "alp")
        .createAlias("activityLog", "al",JoinFragment.LEFT_OUTER_JOIN)
        .setProjection(Projections.projectionList()
                .add(Projections.count("id"), "alpId"));

subquery = subquery.add( Property.forName("al.id").eqProperty("mainAl.id") );

subquery = subquery.add(Restrictions.or(Restrictions.eq("alp.value", UValue), Restrictions.ne("alp.key", "L")));
subquery = subquery.add(Restrictions.or(Restrictions.eq("alp.value", LValue), Restrictions.ne("alp.key", "U")));

Criteria criteria = getCurrentSession().createCriteria(type, "mainAl");

criteria = criteria.add(Subqueries.eq(new Long(2), subquery));
链接地址: http://www.djcxy.com/p/37123.html

上一篇: Hibernate Criteria conditions or subqueries on OneToMany property values

下一篇: Hibernate Criteria Query for multiple columns with IN clause and a subselect