Kunal Batra
Kunal Batra

Reputation: 991

How to define multiple Join on condition using ctiteria API spring data JPA Specification?

Below is the code for fetch join

public static Specification<Item> findByCustomer(User user) {
    return (root, criteriaQuery, criteriaBuilder) -> {
       root.fetch(User_.address, JoinType.LEFT);
        return criteriaBuilder.equal(root.get(User_.id), 1);
    };
}

Above code is generating below query

select us.ALL_COLUMN, adr.ALL_COLUMN from User us left outer join Address adr on us.id= adr.id where us.id = 1;

How can I add multiple condition on left outer join. I want to generate below query using spring data jpa Specification.

Select us.ALL_COLUMN, adr.ALL_COLUMN from User us left outer join Address adr on us.id= adr.id and adr.effect_end_date = null where us.id = 1

Upvotes: 1

Views: 3374

Answers (2)

Adik
Adik

Reputation: 101

public static Specification<A> findAbyBname(String input) {
        return new Specification<A>() {
            @Override
            public Predicate toPredicate(Root<A> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                cq.distinct(true);
                Join<A,AB> AjoinAB = root.joinList(A_.AB_LIST,JoinType.LEFT);
                Join<AB,B> ABjoinB = AjoinAB.join(AB_.B,JoinType.LEFT);
                return cb.equal(ABjoinB.get(B_.NAME),input);
            }
        };
    }

I have something like this. Here are entities:

@Entity
public class A {
    @Id
    private Long id;
    private String name;
    @OneToMany(mappedBy = "a")
    private List<AB> abList;
}
@Entity
public class B {
    @Id
    private Long id;
    private String name;
    @OneToMany(mappedBy = "b")
    private List<AB> abList;
}
@Entity
public class AB {
    @Id
    private Long id;
    private String name;
    @ManyToOne
    @JoinColumn(name = "a_id")
    private A a;
    @ManyToOne
    @JoinColumn(name = "b_id")
    private B b;
}

Upvotes: 1

Pandit Biradar
Pandit Biradar

Reputation: 1877

Below way we can do we should have two predcit and then and for those two perdicate , didnt tested

public static Specification<Item> findByCustomer(User user) {
        return (root, criteriaQuery, criteriaBuilder) -> {
           root.fetch(User_.address, JoinType.LEFT);
    Predicate predicateForEndDate
      = criteriaBuilder.equal(root.get(User_.end_date), null);
    Predicate predicateForUser
      = criteriaBuilder.equal(root.get(User_.id), 1);

            return criteriaBuilder.and(predicateForEndDate, predicateForUser)
        };
    }

Upvotes: 0

Related Questions