简体   繁体   中英

JPA - Oracle bit operations using CriteriaBuilder

I am using CriteriaBuilder to query DB dynamically, all predictions are generated dynamically.

Only problem I am facing now is to transform this native oracle SQL to CriteriaBuilder API.

BITAND example: https://stackoverflow.com/a/10617716/810277

Kindly someone suggest me a way to use JPA CriteriaBuilder.

Thanks in advance.

You can use a math trick to do the same thing (a bit slower though):

Facts:

  • division by 2^х will shift the bits right by x (example 1011010/1000=1011)
  • z mod 2 = 1 if rightmost bit is 1 (example 1011 mod 2 = 1)

So in Criteria API it would be like this:

    int mask = 0b00100;
    Path<Integer> fieldToTest = root.<Integer>get("fieldToTest");
    Expression<Integer> div = cb.quot(fieldToTest, mask).as(Integer.class);
    Expression<Integer> mod = cb.mod(div, 2);
    Predicate maskMatched = cb.equal(mod, 1);

In JPA 2.0 that is not possible within JPQL/Criteria API. You will have to: 1. either do that logic in Java. 2. use native queries for that.

In JPA 2.1 it was introduced the function() method in the Criteria API/JPQL that you could use.

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