1. Create a Specification which would construct a query to pull records from database for a particular jpa entity
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;
public class TravelEntitySpecification {
public static Specification<TravelEntity> filterTravelEntity(final String id,final String empId) {
return new Specification<TravelEntity>() {
@Override
public Predicate toPredicate(Root<TravelEntity> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Predicate predicate = builder.conjunction();
predicate = builder.and(predicate, builder.equal(root.<PK>get(Constant.STRING_ID).get(Constant.STRING_ID), id));
predicate = builder.and(predicate, builder.equal(root.<PK>get(Constant.STRING_ID).get(Constant.DEFV201_empId), empId));
return predicate;
}
};
}
2. Create a Repository interface as like below for the entity
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface TravelEntityRepository extends JpaRepository<TravelEntity, String>, JpaSpecificationExecutor<TravelEntity>{
}
3. Invoke the repository from the dao as like below
public class TravelDAO{
@Autowired
private TravelEntityRepository travelEntityRepository;
public List<TravelEntity> getTravelList(){
return travelEntityRepository.findAll(TravelEntitySpecification.filterTravelEntity("1","2"));
}
public TravelEntity getTravelData(){
return travelEntityRepository.findOne(TravelEntitySpecification.filterTravelEntity("2","2"));
}
No comments:
Post a Comment