【问题标题】:Transient Field in JPA and setting from QueryJPA 中的瞬态字段和查询中的设置
【发布时间】:2014-01-08 21:02:26
【问题描述】:

我们如何从选择查询中加载 JPA 中的瞬态字段。

例如我有这个查询:

SELECT table1.*, (SELECT SUM(field) from table2 WHERE theField=table1.flag) as total FROM table1;

所以在这里我需要一个名为“total”的临时字段在我的 bean 中。

但在 JPA 中似乎是不可能的

【问题讨论】:

    标签: java jpa transient


    【解决方案1】:

    您可以在JPQL 中使用constructor

    查询:

    SELECT NEW com.foo.entities.Table1(table1.*, (SELECT SUM(field) from table2 WHERE theField=table1.flag) as total) FROM table1;
    

    实体:

    @Entity
    public class Table1{
    
    // .. other columns
    
    @Transient
    int total;
    
    // table1Field1,table1Field2 etc. map to your table1.* coulmns
    public Table1(String table1Field1,int table1Field2,int total){
    
    // ..other assignments here
    
    this.total = total; // transient assignment here
    
    }
    
    
    }
    

    【讨论】:

    • 想象我们有一百个豆子,每个豆子有 40 个字段,维护将杀死我们:(
    • 如果我们在这种情况下编写原生 sql 会发生什么?
    • 看来解决方案正在切换到 MyBatis ;)
    • 如何在spring data jpa中使用规范api实现这一点?
    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 2018-03-27
    • 2016-01-28
    • 2012-03-05
    • 2013-09-03
    • 1970-01-01
    • 2019-08-16
    • 2011-01-26
    相关资源
    最近更新 更多