Skip to content

Instantly share code, notes, and snippets.

@ulisseslima
Created April 17, 2019 02:31
Show Gist options
  • Save ulisseslima/7ff9d4ecc49470ccf5c5979b8d806eef to your computer and use it in GitHub Desktop.
Save ulisseslima/7ff9d4ecc49470ccf5c5979b8d806eef to your computer and use it in GitHub Desktop.
Base JPA Repository that supports easier dynamic query building.
package it.murah.license.server.jpa;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
/**
* Makes it easy handling variable property name/values, including inner object
* properties.
* <p>
* e.g.:<br>
* map.put("prop1", 1); <br>
* map.put("child.prop", "foo");
* <p>
* findAllBy(map); // select * from T where prop1=1 and child.prop='foo'
*
* @since 2019-04-16
* @author Ulisses Lima
*/
public class FlexibleJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {
private final EntityManager em;
private final JpaEntityInformation<T, ID> ei;
public FlexibleJpaRepository(JpaEntityInformation<T, ID> ei, EntityManager em) {
super(ei, em);
this.em = em;
this.ei = ei;
}
public List<T> findAllBy(Map<String, Object> params) {
Class<T> type = ei.getJavaType();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> q = cb.createQuery(type);
Root<T> props = q.from(type);
List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
params.forEach((key, val) -> {
String[] path = key.split("\\.");
Path<Object> x = props.get(path[0]);
if (path.length > 1) {
for (int i = 1; i < path.length; i++) {
x = x.get(path[i]);
}
}
predicates.add(cb.equal(x, val));
});
q.where(cb.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()])));
q.orderBy(cb.asc(props.get("id")));
return em.createQuery(q.select(props)).setMaxResults(1000).getResultList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment