具有瞬态属性的Hibernate SQLQuery

时间:2013-11-22 07:35:36

标签: java sql hibernate hibernate-mapping

我需要用db2创建一个hibernate SQLQuery,这个查询返回一些计算出的字段,与数据库中的任何列都没有关系。

目标是在已存在的Java对象中的三个新瞬态字段上设置SQLQuery的这些sum()计算的值。

SQLQuery使用语法:

SELECT id as {entityObject.id},
           name as {entityObject.name},
           order as {entityObject.order},
           SUM(CASE
           WHEN pv.value_id = 1 
            AND pv.value=1 THEN 1 ELSE 0 END) AS {entityObject.someCount}

问题是Hibernate抱怨并说需要someCount的列。似乎没有帮助将java字段声明为 transient ,甚至不使用javax.persistence中的 @Transient 注释在同一时间。

如果我只在hbm.xml映射文件中声明:

<property name="id" type="java.lang.Integer" column="someColumn" />
<!-- Some more fields here -->

<!-- THE IMPORTANT ONE -->
<property name="someCount" type="java.lang.Integer"/>

Java对象:

public class EntityObject implements Serializable {

private static final long serialVersionUID = 1479579608940145961L;

private Integer id;
private String name;
private Integer order;

    // This is the one giving me hell. I've tried with @Transient also
private transient Integer someCount;

public Category() {
}

public Category(final String name, final Integer order) {
    this.name = name;
    this.order = order;
}

public Integer getOrder() {
    return this.order;
}

public void setOrder(final Integer order) {
    this.order = order;
}

public Integer getId() {
    return this.id;
}

public String getName() {
    return this.name;
}

public void setName(final String name) {
    this.name = name;
}


public Integer getSomeCount() {
    return someCount;
}

public void setSomeCount(final Integer count) {
    this.someCount = count;
}


}

它要求我提供一个列,我尝试插入一个假列,但它不起作用。问题是我希望这些'count'字段只能从SQLQuery设置,并且在来自常规Hibernate查询时为空和null。

我查看了docs和google搜索,似乎你可以通过不在hibernate映射文件中声明它来声明字段瞬态,但是它不会在“as {entityObject”上将它设置在对象上。 someCount}“即使我声明了getter / setters。

请帮助。 非常感谢提前。

2 个答案:

答案 0 :(得分:2)

可以直接从数据库执行所有这些操作而不必发出其他查询的唯一选项是Hibernate Formula属性:

http://wiki.jrapid.com/w/Formula_(attribute_of_property)

<property name="someCount" formula="select count(*) from some_table where table_key = ?"/>

?将使用当前实例的ID自动填充占位符。

答案 1 :(得分:1)

1创建POJO:

public class SumValue{
   private BigInteger myId; 
   private String myName;
   private BigInteger myOrder;
   private BigInteger mySum;
   ....
   getters and setters here
   ....
}

2您的查询中的细微更改

SELECT id as "myId",
       name as "myName",
       order as "myOrder",
       SUM(CASE
       WHEN pv.value_id = 1 
        AND pv.value=1 THEN 1 ELSE 0 END) AS "mySum"

3执行本机sql

     List<SumValue> jobStateViewList = (List<SumValue>)getSessionFactory().getCurrentSession()
                                   .createSQLQuery(yourQuery)
                                   .setResultTransformer(
                                        new AliasToBeanResultTransformer(SumValue.class)
                                   ).list();