CriteriaBuilder cast function example

Hi, everyone.

I’m struggling right now trying to call an SQL cast function in a ‘JPA Criteria’ way.

To put some context, what I have is a table like this:

create table accounts
    id  bigint generated by default as identity primary key,
    customerid  varchar(255),
    description varchar(255)

Mapped to a class like:

@Table(name = "accounts")
public class Account {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String customerId;
    private String description;

    //constructors, setters, and getters...


And with test data like this:

|1 |2         |First      |
|2 |3         |Second     |
|3 |25        |Third      |
|4 |38        |Fourth     |
|5 |900123456 |Fifth      |

What I need to achieve is to be able to design a criteria query that can make an “ge” evaluation over the customerId field. With what I ended, it’s something like this:

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
Root<Account> root = cq.from(Account.class);
List<Predicate> predicates = new ArrayList<>();
Object value = 20; //I need to use this Object type because it is an objective of the proof of concept itself
predicates.add("cast", Integer.class, root.get("customerId"), /*???*/), (Integer) value));

Query<Account> query = session.createQuery( Predicate[0])));

I don’t know if I’m facing it in the right way. I need an example of calling a cast function like this, or any suggestion pointing me in the right direction at least. Maybe I have another problem with the predicate itself.

Put in simple words, what I need is a “Criteria” way to get a query like this:

session.createQuery("select a from Account a order by cast(a.customerId as integer)", Account.class);

Thank you in advance.

It’s quite simple, there is an as method on Expression which allows to do casts:

predicates.add("customerId").as(Integer.class), (Integer) value));
1 Like

Thank you very much! I definitively misunderstood the as method functionality.