Search code examples
jpacriteria-api

How to access the column of joined entity using JPA Specification?


I am creating a specification which returns the Parent entity's records based on Child entity's type column. These 2 entities have One-to-One mapping, so I am joining them.

But the problem is that type column is inside the embedded id of Child entity.

My code snippet is below:

return (root, query, criteriaBuilder) -> {
        Join<Parent, Child> join = root.join("child");
        return criteriaBuilder.equal(join.get("id.type"), val);
    };

I haven't got any success with it yet. How do I access the type column correctly to make my code work?


Solution

  • I found that the following code makes it work -

    return (root, query, criteriaBuilder) -> {
        Join<Parent, Child> join = root.join("child");
        Join<Child, ChildPK> joinId = join.join("id");
        return criteriaBuilder.equal(joinId.get("type"), val);
    };
    

    Here ChildPK is the embedded id.