Home > Software design >  Spring JPA CriteriaBuilder not producing correct SQL
Spring JPA CriteriaBuilder not producing correct SQL

Time:11-12

I have the following criteria builder statement:

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TestEntity> criteriaQuery = criteriaBuilder.createQuery(TestEntity.class);
    Root<TestEntity> itemRoot = criteriaQuery.from(TestEntity.class);
    criteriaQuery.select(itemRoot);

    javax.persistence.criteria.CriteriaBuilder.In inClause = criteriaBuilder.in(itemRoot.get("cost"));
    inClause.value(criteriaBuilder.literal(5.0d));

    javax.persistence.criteria.CriteriaBuilder.In inClause2 = criteriaBuilder.in(itemRoot.get("cost"));
    inClause2.value(criteriaBuilder.literal(5.0d));

    Predicate pred = criteriaBuilder.or(inClause, criteriaBuilder.and(inClause2, criteriaBuilder.like(itemRoot.get("name"), "%name%")));
    criteriaQuery.where(pred);
    TypedQuery typedQuery = entityManager.createQuery(criteriaQuery);
    List<TestEntity> list = typedQuery.getResultList();

Which produces the following sql :

select *
from test_entity testentity0_ 
where
    testentity0_.cost in (
        5.0
    ) 
    or (
        testentity0_.cost in (
            5.0
        )
    ) 
    and (
        testentity0_.name like ?
    )

but the where clause is wrong, i would expect the following :

select *
from test_entity testentity0_ 
where
    testentity0_.cost in (
        5.0
    ) 
    or (
        testentity0_.cost in (
            5.0
        )
        and (
            testentity0_.name like ?
        )
    ) 

The and is misplaced, it should go inside the second expression of the or statement

CodePudding user response:

Both expressions are equivalent since and operator has precedence on or:

A or B and C is equivalent to A or (B and C)

  • Related