47

假设有一张桌子:

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;
4

3 回答 3

117

它已被添加到 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

于 2011-09-05T13:17:45.090 回答
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();
于 2010-02-23T13:06:34.023 回答
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 不会保留在数据库中)

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

于 2009-02-05T19:23:11.133 回答