|
| 1 | +package org.baeldung.persistence.criteria.dao; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +import javax.persistence.EntityManager; |
| 7 | +import javax.persistence.TypedQuery; |
| 8 | +import javax.persistence.criteria.CriteriaBuilder; |
| 9 | +import javax.persistence.criteria.CriteriaQuery; |
| 10 | +import javax.persistence.criteria.Predicate; |
| 11 | +import javax.persistence.criteria.Root; |
| 12 | + |
| 13 | +import org.baeldung.persistence.criteria.model.Book; |
| 14 | +import org.baeldung.persistence.criteria.repository.BookRepositoryCustom; |
| 15 | +import org.springframework.stereotype.Repository; |
| 16 | + |
| 17 | +@Repository |
| 18 | +public class BookRepositoryImpl implements BookRepositoryCustom { |
| 19 | + |
| 20 | + private EntityManager em; |
| 21 | + |
| 22 | + public BookRepositoryImpl(EntityManager em) { |
| 23 | + this.em = em; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public List<Book> findBooksByAuthorNameAndTitle(String authorName, String title) { |
| 28 | + CriteriaBuilder cb = em.getCriteriaBuilder(); |
| 29 | + CriteriaQuery<Book> cq = cb.createQuery(Book.class); |
| 30 | + |
| 31 | + Root<Book> book = cq.from(Book.class); |
| 32 | + List<Predicate> predicates = new ArrayList<>(); |
| 33 | + |
| 34 | + if (authorName != null) { |
| 35 | + predicates.add(cb.equal(book.get("author"), authorName)); |
| 36 | + } |
| 37 | + if (title != null) { |
| 38 | + predicates.add(cb.like(book.get("title"), "%" + title + "%")); |
| 39 | + } |
| 40 | + cq.where(predicates.toArray(new Predicate[0])); |
| 41 | + |
| 42 | + TypedQuery<Book> query = em.createQuery(cq); |
| 43 | + return query.getResultList(); |
| 44 | + } |
| 45 | + |
| 46 | +} |
0 commit comments