简体   繁体   中英

Using native sql in java criteria predicate

I have a predicate( javax.persistence.criteria.Predicate ) which filters raw data as follows:

    public Predicate byAccountsId(Collection<Long> accountsId) {
        ParameterExpression<?> param = createParam(AOraArrayUserType.class, new AOraArrayUserType(accountsId));
        return criteriaBuilder().or(
                criteriaBuilder()
                        .equal(criteriaBuilder().function("in_ex", Long.class, actSourceJoin().get(Account_.id),
                                param), 1),
                criteriaBuilder().equal(
                        criteriaBuilder().function("in_ex", Long.class, actDestinationJoin().get(Account_.id),
                                param), 1));
    }

This predicate builds the next part of the query:

..
where
..
act.source_id in (accountsId.values())
or act.destination_id in (accountsId.values() - array ids)
..

It works fine but there may be too much raw data.I want to use "Oracle functional index", which removes unnecessary data from the query results. I tried to rewrite my predicate as follows:

    public Predicate byAccountsId(Collection<Long> accountsId) {
        ParameterExpression<?> param = createParam(AOraArrayUserType.class, new AOraArrayUserType(accountsId));
        return criteriaBuilder().or(
                criteriaBuilder().literal(
                        Restrictions.sqlRestriction("case when state != 'ARCHIVE' then source_id else null end"))
                        .in(param));
    }

Resurlt query builds fine but returns no result. But when I copy result query to sql developer and run the query it returns the expected result.

Part of the query which is build by new predicate:

..
where 
..
(case when act.state != 'ARCHIVE' then act.source_id else null end) in (accountsId.values() - array ids)
..

Does anybody know why I don't get the correct result when I'm using the new predicate? And can I use hibernate.criterion.Restrictions with javax.persistence.criteria.Predicate ?

您可以在实体(AOraArrayUserType)中为表达式定义@Formula并在条件中使用该字段

Restrictions.in("theFormulaField", param)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM