Skip to content

Instantly share code, notes, and snippets.

@augustovictor
Created January 28, 2020 11:14
Show Gist options
  • Save augustovictor/e7fc5c6bbd684acfdd29c3bc5cbf33d4 to your computer and use it in GitHub Desktop.
Save augustovictor/e7fc5c6bbd684acfdd29c3bc5cbf33d4 to your computer and use it in GitHub Desktop.
@Repository
@Transactional
public class SingerServiceImpl implements SingerService {
final static String ALL_SINGER_NATIVE_QUERY =
"select id, first_name, last_name, birth_date, version from singer";
private Log log =
LogFactory.getLog(SingerServiceImpl.class);
@PersistenceContext
private EntityManager em;
...
@Transactional(readOnly=true)
@Override
public List<Singer> findByCriteriaQuery(String firstName, String lastName) {
log.info("Finding singer for firstName: " + firstName
+ " and lastName: " + lastName);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Singer> criteriaQuery = cb.createQuery(Singer.class);
Root<Singer> singerRoot = criteriaQuery.from(Singer.class);
singerRoot.fetch(Singer_.albums, JoinType.LEFT);
singerRoot.fetch(Singer_.instruments, JoinType.LEFT);
criteriaQuery.select(singerRoot).distinct(true);
Predicate criteria = cb.conjunction();
if (firstName != null) {
Predicate p = cb.equal(singerRoot.get(Singer_.firstName),
firstName);
criteria = cb.and(criteria, p);
}
if (lastName != null) {
Predicate p = cb.equal(singerRoot.get(Singer_.lastName),
lastName);
criteria = cb.and(criteria, p);
}
criteriaQuery.where(criteria);
return em.createQuery(criteriaQuery).getResultList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment