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:

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

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

    //constructors, setters, and getters...

}

And with test data like this:

+--+----------+-----------+
|id|customerid|description|
+--+----------+-----------+
|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(cb.ge(cb.function("cast", Integer.class, root.get("customerId"), /*???*/), (Integer) value));

Query<Account> query = session.createQuery(cq.select(root).where(predicates.toArray(new Predicate[0])));
query.getResultList().forEach(System.out::println);

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.

UPDATE:
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(cb.ge(root.get("customerId").as(Integer.class), (Integer) value));
1 Like

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