1
I’m trying to do a survey using Criteria, the research would be this:
SELECT *
FROM lefacil.pap_produto a
WHERE (a.marca='Fabber Castell' or a.marca='Tilibra') AND (a.quantidadeCores='12 Cores' or a.quantidadeCores='24 Cores');
I have already researched and made several tests, but I could not get the result of the above search. Follow the class I’m using to do the tests
public class TesteBancoCriteriaPredicateComArray {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("LefacilPU");
EntityManager manager = factory.createEntityManager();
EntityTransaction trx = manager.getTransaction();
trx.begin();
CriteriaBuilder cb = manager.getCriteriaBuilder();
CriteriaQuery<ProdutoPap> cq = cb.createQuery(ProdutoPap.class);
Root<ProdutoPap> root = cq.from(ProdutoPap.class);
// parametros
ArrayList<String> param1 = new ArrayList<>();
//aqui coloquei somente um objeto para teste, mas preciso que seja um Array
param1.add("Fabber Castell");
ArrayList<String> param2 = new ArrayList<>();
param2.add("24 Cores");
param2.add("12 Cores");
List<Predicate> predicates = new ArrayList<Predicate>();
if (param1 != null) {
predicates.add(cb.equal(root.get("marca"), param1));
}
if (param2 != null) {
Iterator<String> a = param2.iterator();
while (a.hasNext()) {
predicates.add(cb.equal(root.get("quantidadeCores"), a.next()));
}
}
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
System.out.println(manager.createQuery(cq).getResultList());
trx.commit();
}
}
What I want is a correct way to do the above research using Criteria.
Any specific reason for wanting the consultation on Criteria?
– Felipe Marinho
I’m setting up a system, and in these researches where I need to search for several parameters I think it’s much better to make use of Criteria.
– Edjane