How to set true with CriteriaUpdate?

973 views Asked by At

I have an Entity who has a boolean property.

class MyEntity {
    @Basic(optional = false)
    @Column(name = "FLAG")
    private boolean flag;
}

How can I execute a bulk update setting the flag field with true?

// UPDATE MyEntity AS e SET e.flag = TRUE
final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaUpdate<MyEntity> update
    = builder.createCriteriaUpdate(MyEntity.class);
final Root<MyEntity> root = criteriaUpdate.from(MyEntity.class);
update.set(root.get(ProfileClue_.flag), ???);
1

There are 1 answers

0
Neil Stockton On BEST ANSWER

Using pure JPA I would do something like

final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaUpdate<MyEntity> update = builder.createCriteriaUpdate(MyEntity.class);
final Root<MyEntity> root = criteriaUpdate.from(MyEntity.class);
Expression trueLiteral = builder.literal(Boolean.TRUE);
update.set(root.get(ProfileClue_.flag), trueLiteral);

Using a more advanced JPA provider that supports parameters in other parts of the query than the JPA spec mandates (supported by DataNucleus JPA, and maybe others), you can make it a parameter.

final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaUpdate<MyEntity> update = builder.createCriteriaUpdate(MyEntity.class);
final Root<MyEntity> root = criteriaUpdate.from(MyEntity.class);
ParameterExpression<String> param = builder.parameter(Boolean.class, "myParam");
update.set(root.get(ProfileClue_.flag), param);