JPQL - Update with Multiple where conditions

泄露秘密 提交于 2019-12-12 00:23:44

问题


Does JPQL support the following Update?

Update Person p set p.name = :name_1 where p.id = :id_1,
                    p.name = :name_2 where p.id = :id_2,
                    p.name = :name_3 where p.id = :id_3

If not, are there any alternatives? I tried it myself. But createQuery returned null.


回答1:


Case expression is supported in JPA 2.0. I have provided pseudo-code, can make modifications accordingly.

  • You can try below JPQL query using CASE.

    Update Person p set p.name = CASE WHEN (p.id = :id1) THEN :name_1 WHEN (p.id = :id2) THEN :name_2 WHEN (p.id = :id3) THEN :name_3 END

    general_case_expression::= CASE WHEN conditional_expression THEN scalar_expression ELSE scalar_expression END

  • Else, can try Criteria API to build the query.

    when(Expression condition, R result) : Add a when/then clause to the case expression.

    criteriaBuilder.selectCase().when(criteriaBuilder.equal(person.get("id"), id1), name_1);



来源:https://stackoverflow.com/questions/17581840/jpql-update-with-multiple-where-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!