user373201
user373201

Reputation: 11435

JPA CriteriaBuilder case query

Can anyone provide an example of how to write a case query using CriteriaBuilder?

Upvotes: 3

Views: 6176

Answers (2)

Manu
Manu

Reputation: 3635

I could not find "caseStatement" in JPA 2.0 Criteria API. Seems its EclipseLink specific. The correct way is to use "builder.selectCase()"

See the section "Case Expressions" in Pro JPA 2: Mastering the Java Persistence API

Upvotes: 6

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47913

What follows is a sample case expression using CriteriaBuilder (this works in JPA 2):

Hashtable caseTable = new Hashtable(3);
caseTable.put("Bob", "Bobby");
caseTable.put("Susan", "Susie");
caseTable.put("Eldrick", "Tiger");
Expression expression = builder.get("firstName").caseStatement(caseTable, "NoNickname").equal("Bobby");

It generates the following SQL query:

"CASE t1.firstName WHEN 'Bob' THEN 'Bobby' WHEN 'Susan' THEN 'Susie' WHEN 'Eldrick' THEN 'Tiger' ELSE 'NoNickname' END = 'Bobby'"

For more info please see JPA 2.0 Case Expressions.

Upvotes: 8

Related Questions