I took some JPA handouts and read some tutorials on the internet, but I'm still a bit lost with regard to disjunction and conjunction in JPA.
From what I understand the conjunction serves to group conditions with the "AND" of the sql, since the disjunction serves to group conditions with "OR". Am I right? The material I searched for seems very confusing.
I then tried to make the criteria generate queries with the following pattern:
WHERE (condicao1 = valor1 AND condicao2 = valor2) or (condicao3=valor3 and condicao4=valor4)
However I was not successful with my implementation:
EntityManager em = JPAUtil.getEntityManager();
// Instanciar o BUILDER de criteria
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
//Cria uma criteria query que trabalha com Conta
CriteriaQuery<Conta> cquery = criteriaBuilder.createQuery(Conta.class);
//Obter RAIZ da query que consulta da entidade CONTA
Root<Conta> root = cquery.from(Conta.class);
Path<String> titularPath = root.<String>get("titular");
Path<Integer> idPath = root.<Integer>get("id");
Path<String> numeroPath = root.<String>get("numero");
Path<String> bancoPath = root.<String>get("banco");
Predicate titularIgual = criteriaBuilder.like(titularPath, "M%");
Predicate idIgual = criteriaBuilder.equal(idPath, 1);
Predicate idDiferente = criteriaBuilder.equal(idPath, 500);
//Conjuncao1 seria (idDiferente AND titularIgual) ???
Predicate conjuncao1 = criteriaBuilder.conjunction();
conjuncao1 = criteriaBuilder.and(conjuncao1,idDiferente);
conjuncao1 = criteriaBuilder.and(conjuncao1,titularIgual);
//Conjunao2 seria (idIgual AND titularIgual) ???
Predicate conjuncao2 = criteriaBuilder.conjunction();
conjuncao2 = criteriaBuilder.and(conjuncao2,idIgual);
conjuncao2 = criteriaBuilder.and(conjuncao2,titularIgual);
//Se minha logica estiver correta entao a disjuncao das duas conjuncoes deveria ser
// (idDiferente AND titularIgual) or (idIgual AND titularIgual) Não?
Predicate disjuncao = criteriaBuilder.disjunction();
disjuncao = criteriaBuilder.or(conjuncao1,conjuncao2);
cquery.where(disjuncao);
TypedQuery<Conta> tQuery = em.createQuery(cquery);
List<Conta> contas = tQuery.getResultList();
I did not understand the fact that Hibernate generated the query below:
where
1=1
and conta0_.id=500
and (
conta0_.titular like ?
)
or 1=1
and conta0_.id=1
and (
conta0_.titular like ?
)
This does not make sense in my understanding of conjunction ... I believe both conditions: "account.Id = 1 and account.title =?" should be out of kinship or even be both under the same parentage.
Did I get it right this conjunction story?