Reputation: 1794
I followed this tutorial to get Spring Data JPA Specifications: https://dzone.com/articles/using-spring-data-jpa-specification
It worked to implement that for me, but I can't call the specifications methods to search for them. I want to have them in my SearchController:
Code:
TelefonbuchSpecifications:
public static Specification<Telefonbuch> hasVorname(String vorname) {
return (root, query, cb) -> {
return cb.equal(root.get(Telefonbuch_.vorname), "%"+vorname.toLowerCase()+"%");
};
}
And now I want to call this method in my SearchController (SucheController), but I don't know how. At the moment the method looks like this: SucheController:
public void search(String vorname, String nachname, String telefonnummer, String handynummer) {
telefonbuch.setVorname(vorname);
telefonbuch.setNachname(nachname);
telefonbuch.setTelefonnummer(telefonnummer);
telefonbuch.setHandynummer(handynummer);
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Telefonbuch> query = builder.createQuery(Telefonbuch.class);
Root<Telefonbuch> root = query.from(Telefonbuch.class);
List<Predicate> predicates = new ArrayList<Predicate>();
if (!vorname.isEmpty()) {
//eintraege = telefonbuchRepository.findAll(hasVorname()); -> does not work
Predicate condition = builder.like(builder.lower(root.get(Telefonbuch_.vorname)), "%"+vorname.toLowerCase()+"%");
predicates.add(condition);
}
...
query.select(root).where(predicates.toArray(new Predicate[predicates.size()]));
Upvotes: 0
Views: 2192
Reputation: 16131
You need to have a a TelefonbuchRepository interface which implements JpaRepository
and JpaSpecificationExecutor
. The latter gives you methods, to which you can pass your Specification
:
- long count(Specification<T> spec)
- List<T> findAll(Specification<T> spec)
- Page<T> findAll(Specification<T> spec, Pageable pageable)
- List<T> findAll(Specification<T> spec, Sort sort)
- Optional<T> findOne(Specification<T> spec)
Edit: MySpecification:
public class MyEntitySpecification implements Specification<MyEntity> {
private final String searchText;
public MyEntitySpecification(String searchText) {
this.searchText = searchText;
}
@Override
public Predicate toPredicate(Root<MyEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<>();
Optional.ofNullable(searchText).ifPresent(
s -> predicates.add(cb.like(cb.lower(root.get(MyEntity_.searchString)), "%" + s.toLowerCase() + "%"))
);
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
}
Upvotes: 1