Sunday, 1 May 2016

How to use Specification in Spring JPA


Create specification like below

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

public class TravelDetailSpecification {

public static Specification<TravelDetail> applyTravelDetailQuery() {
return new Specification<TravelDetail>() {
@Override
public Predicate toPredicate(Root<TravelDetail> root,
CriteriaQuery<?> query, CriteriaBuilder builder) {
Predicate predicate = builder.conjunction();
final Join<TravelDetail, TravelDetailCode> travelDetailCode = root
.join(TravelDetail_.id, JoinType.LEFT);

predicate = builder.and(predicate, builder
.isNotNull(travelDetailCode
.<String> get(TravelDetailCode_.price)));

predicate = builder.and(predicate, builder.equal(root.get(TravelDetail.id), id));

query.orderBy(builder.asc(root.get(TravelDetail_.place)));

return predicate;
}
};
}

}

Create entity like below
@Entity
@Table(name="TRAVEL_DETAIL", schema="TRAVEL")
@NamedQuery(name="TravelDetail.findAll", query="SELECT f FROM TravelDetail f")
public class TravelDetail implements Serializable {
private static final long serialVersionUID = 1L;

@Id
private long id;

private string package;

private BigDecimal price;

//get set methods
}

No comments:

Post a Comment