将基于JOIN的聚合查询的结果映射到Hibernate属性

时间:2014-07-03 08:41:47

标签: java sql hibernate hql

我需要获得聚合函数的结果到实体属性。我尝试使用Hibernate的@Formula anotation,但她显然遇到了JOIN问题。有没有其他方法可以将这些查询的结果转化为对象的适当性?

简化数据模型

    @Entity 
    @Table(name = "quasar_auditor")
    class Auditor(){
        @Id
        private Long id;
        // ...
    }

    @Entity 
    @Table(name = "quasar_nando_code")
    class NandoCode{

        @Id
        private Long id;

        @ManyToOne
        @JoinColumn(name = "parent_id") 
        private NandoCode parent;

        @OneToMany(mappedBy = "parent")
        private Set<NandoCode> children;
        // ...
    }

    @Entity
    @Table(name = "quasar_auditor_has_nando_code")
    class AuditorNandoCode{

        @Id
        private Long id;
        private Auditor auditor;

        @ManyToOne(cascade = CascadeType.DETACH)
        @JoinColumn(name = "nando_code_id")
        private NandoCode nandoCode;
        private int categorySpecificTraining;

        //  ERROR: missing FROM-clause entry for table "nandocode"
        @Formula(value = "(select COALESCE(sum(anc.category_specific_training),0) from quasar_auditor_has_nando_code anc "+
                         "inner join quasar_nando_code nc ON anc.nando_code_id=nc.id "+
                         "where nc.parent_id = nandoCode.id and anc.auditor_id = auditor.id)")
        private int childrenCategorySpecificTraining;


        // getter/setters...
    }

nandoCode.idauditor.id是此对象的属性;

感谢您的建议

1 个答案:

答案 0 :(得分:1)

首先,此查询范围中没有nanoCode.idauditor.id这样的内容。

如果您尝试访问@Formula注释中AuditorNandoCode内的AuditorNandoCode.auditor.id,您应该只使用列名 - 在这种情况下,可能是auditor_id

所以,试试这个注释:

@Formula(value = "(select COALESCE(sum(anc.category_specific_training),0) from quasar_auditor_has_nando_code anc "+
                     "inner join quasar_nando_code nc ON anc.nando_code_id=nc.id "+
                     "where nc.parent_id = nandoCode_id and anc.auditor_id = auditor_id)")