Is there such thing CASE expression in JPQL?

前端 未结 3 1314
迷失自我
迷失自我 2020-12-01 04:06

Let say there is a table:

TableA:Field1, Field2, Field3

and associated JPA entity class

@Entity
@Table(name=\"TableA\")
pub         


        
相关标签:
3条回答
  • 2020-12-01 04:47

    It has been added in JPA 2.0

    Usage:

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

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

    0 讨论(0)
  • 2020-12-01 04:58

    There is certainly such thing in Hibernate so when you use Hibernate as your JPA provider then you can write your query as in this example:

        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();
    
    0 讨论(0)
  • 2020-12-01 05:07

    You can use the event listeners provided by Jpa to do something when you load one row of the db, ie:

    @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;
                }
            }
        }
    }
    

    (the field4 not persist in the db)

    (take this like an workaround to "non implemented feature in JPA" like case statements)

    0 讨论(0)
提交回复
热议问题