在JPQL中有这样的CASE表达吗?

时间:2009-01-09 09:00:42

标签: java oracle orm jpa

假设有一张表:

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;

3 个答案:

答案 0 :(得分:85)

已在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

答案 1 :(得分:1)

当您加载数据库的一行时,您可以使用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...

    @Transient
    private String field4;

    @PostLoad
    private void onLoad() {
        if (field2 != null) {
            switch (field2.intValue()) {
            case 1:
                field4 = "One";
                break;
            case 2:
                field4 = "Two";
                break;
            default:
                field4 = "Other Number";
                break;
            }
        }
    }
}

(field4不会在db中持久存在)

(将此解释为“JPA中未实现的功能”的解决方法,如案例陈述)

答案 2 :(得分:1)

在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();