【问题标题】:Is there such thing CASE expression in JPQL?JPQL 中有这样的 CASE 表达式吗?
【发布时间】:2010-09-30 10:59:48
【问题描述】:

假设有一张桌子:

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;

【问题讨论】:

    标签: java oracle orm jpa


    【解决方案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();
    

    【讨论】:

      【解决方案3】:

      你可以使用Jpa提供的事件监听器在加载一行db时做一些事情,即:

      @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 不保存在数据库中)

      (将其视为“JPA 中未实现的功能”的解决方法,如案例语句)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-05
        • 1970-01-01
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        • 1970-01-01
        • 2020-07-03
        • 2021-03-26
        相关资源
        最近更新 更多