8

The documentation says:

Create an expression for a literal

In the code I see such uses of cb.literal():

  Expression<String> wordLiteral = cb.literal(word);
  predicates.add(cb.like(namePath, wordLiteral));

But if omit wordLiteral here and use word instead, nothing changes. So what is this method for?

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
Ekaterina
  • 1,642
  • 3
  • 19
  • 36

1 Answers1

4

In case of like it works, because it does have overloaded version that takes String as an argument.

There are several other methods for Predicate creation that accept only expressions.

For the sake of example lets take length. There is only one, and it takes Expression<String> as an argument. If we have entity User with field account and based on user input we must find users whose account has same length, that can be done as follows:

String accountInput = "Jack";

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);

Root<User> root = cq.from(User.class);

cq.select(root)
   .where(
        cb.equal(
            cb.length(root.get("account")),
            cb.length(cb.literal(accountInput))
        )
);
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135