Amulya
Amulya

Reputation: 31

how to write this query using jpa criteria api?

Select c.id,
    (Select c2.value from customer_table c2 Where c2.id = c.id And c2.key = 'test') as "test",
    (Select c2.value from customer_table c2 Where c2.id = c.id And c2.key = 'service-category') as "service-category",
    (Select c2.value from customer_table c2 Where c2.id = c.id And c2.key = 'exam') as "exam"
From customer_table c
Group By c.id;

Upvotes: 1

Views: 468

Answers (1)

JLazar0
JLazar0

Reputation: 1292

Assuming the existence and correct modeling of the customerTable entity, its relationships and that value is of type String, the implementation would be like this:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<YourPojo> cq = cb.createQuery(YourPojo.class);

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

//Subquery 1
Subquery<String> sqVal1 = cq.subquery(String.class);
Root<CustomerTable> sq1Root = sqVal1.from(CustomerTable.class);
sqVal1.where(
    cb.and(
        cb.equal(root.get("id"),sq1Root.get("id")),
        cb.equal(sq1Root.get("key"),"test")
    )
);
sqVal1.select(sq1Root.get("value"));

//Subquery 2
Subquery<String> sqVal2 = cq.subquery(String.class);
Root<CustomerTable> sq2Root = sqVal2.from(CustomerTable.class);
sqVal2.where(
    cb.and(
        cb.equal(root.get("id"),sq2Root.get("id")),
        cb.equal(sq2Root.get("key"),"service-category")
    )
);
sqVal2.select(sq2Root.get("value"));

//Subquery 3
Subquery<String> sqVal3 = cq.subquery(String.class);
Root<CustomerTable> sq3Root = sqVal3.from(CustomerTable.class);
sqVal3.where(
    cb.and(
        cb.equal(root.get("id"),sq3Root.get("id")),
        cb.equal(sq3Root.get("key"),"exam")
    )
);
sqVal3.select(sq3Root.get("value"));

cq.groupBy(root.get("id"));

cq.multiselect(
    root.get("id"),
    sqVal1.getSelection(),
    sqVal2.getSelection(),
    sqVal3.getSelection()
);

You need a pojo with a constructor with the same parameters (in order and type) as the multiselect clause

public class YourPojo {
    public YourPojo(String id, String val1, String val2, String val3){
       [...]
    }
}

It is recommended to use metamodels to access the properties of the entities, which would lead to replace the following code

root.get("id");

with this other

root.get(CustomerTable_.id);

One of the many advantages of using metamodels without getting too into the subject is the ability to auto-complete the property name and reduce the chance of error at this point.

Upvotes: 3

Related Questions