简体   繁体   中英

Select query with JPA Criteria API When Entity class has a child class (Embeddable id)

I am new to JPA.

I have found how to use JPA criteria API in the below link: JPA Criteria API with multiple parameters

The code for predicate is:

Root<CustomerEntity > customerEntity = cq.from(CustomerEntity.class);
List<Predicate> predicates = new ArrayList<Predicate>();
//Adding predicates in case of parameter not being null
    if (param1 != null) {
        predicates.add(
                qb.equal(customerEntity.get("fieldName"), param1));
    }

But my customer entity class has a embeddable id (composite primary key)

How can I use JPA criteria API in this scenario

Are all the embeddable id object values mandatory for searching as well(Select query)?

You have to do 2 steps:

Implement equals and hashcode on your embeddable object

Create predicate like normal

  predicates.add(
            qb.equal(customerEntity.get("id"), embeddableId));

Update You cannot search by the whole object without filling all its values. To search for just one property, just go through the path and compare

predicates.add(
            qb.equal(customerEntity.get("id").get("property1"), embeddableId.getProperty1()));

Hope this will help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM