JPQL中有CASE表达式吗?

2022-08-31 22:19:57

假设有一个表:

TableA:Field1, Field2, Field3

和关联的 JPA 实体类

@Entity
@Table(name="TableA")
public class TableA{
  @Id
  @Column(name="Field1")
  private Long id;

  @Column(name="Field2")
  private Long field2;

  @Column(name="Field3")
  private Long field3;

  //... more associated getter and setter...
}

有没有办法构造一个松散地转换为此SQL的JPQL语句,即如何将case表达式转换为JPQL?

select field1,
case
  when field2 = 1 then 'One'
  when field2 = 2 then 'Two'
  else 'Other number'
end,
field3
from tableA;

答案 1

它已添加到 JPA 2.0 中

用法:

SELECT e.name, CASE WHEN (e.salary >= 100000) THEN 1 WHEN (e.salary < 100000) THEN 2 ELSE 0 END FROM Employee e

编号: http://en.wikibooks.org/wiki/Java_Persistence/JPQL_BNF#New_in_JPA_2.0


答案 2

在Hibernate中肯定有这样的事情,所以当你使用Hibernate作为你的JPA提供者时,你可以编写你的查询,如这个例子所示:

    Query query = entityManager.createQuery("UPDATE MNPOperationPrintDocuments o SET o.fileDownloadCount = CASE WHEN o.fileDownloadCount IS NULL THEN 1 ELSE (o.fileDownloadCount + 1) END " +
                                            " WHERE o IN (:operations)");
    query.setParameter("operations", mnpOperationPrintDocumentsList);

    int result = query.executeUpdate();

推荐