Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we build Spring Data JPA specification out of a composite key attribute

I am using Spring Data JPA specifications for generic queries to my entities. So far it has worked well. Now the problem happened when I try to use these on composite keys used via embeddedId annotation. So here I need to use a nested property to query which say if the object is Foo and I am trying to write a criteria over id. id1 for example.

@Entity
@Data
public class Foo implements Serializable {
    private static final long serialVersionUID = 1L;
     /** The key. */
   @EmbeddedId
   private FooKey id;
}

@Embeddable
@Data
public class FooKey implements Serializable {
    private static final long serialVersionUID = 1L;
     /** The key. */

   private String id1;
   private String id2;
}

In the specification I am trying to do

@Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
 // get root type 
 root.get(property).getJavaType()

But this doesn't work for nested attributes like in this case. Is there any way I can be able to build predicates for properties in the composite key.

like image 445
Gaurav Rawat Avatar asked Dec 18 '22 18:12

Gaurav Rawat


1 Answers

Example of Equal:

     @Override
     public Predicate toPredicate(Root<Foo> root, CriteriaQuery<?> query, CriteriaBuilder builder) { 
     builder.equal(root.get("id").get("id1"),"my val");
like image 157
Rafik BELDI Avatar answered Jan 13 '23 10:01

Rafik BELDI