如何创建一个hibernate不同的查询

时间:2011-02-15 03:50:48

标签: mysql hibernate

我浏览了一下网络,无法真正找到答案。

我有两个表A和B. B是A的孩子。我需要根据A的一些限制从B中获取不同属性的列表。

例如:

SQL:

select distinct sirm.attribute
from store_item_received_material sirm
where sirm.store_item_id in (select si.id from store_item si where si.program_id = 9 and si.customer_id = 1 and si.date_processed is not null);

当然,SQL效果很好。

现在,我需要在我的项目中运行它。

我正在运行hibernate 3.3.1。我尝试了以下方法:

@NamedNativeQueries ({
    @NamedNativeQuery (name = "select.distinct.sirm.for.customer.program", query = "select distinct(sirm.attribute) as attribute from store_item_received_material as sirm where sirm.store_item_id in (select si.id from store_item as si where si.customer_id = ? and si.program_id = ? and si.date_processed is not null)")
})

但是由于以下错误而失败:

嵌套异常是org.hibernate.cfg.NotYetImplementedException:尚不支持纯本机标量查询

所以我尝试了以下内容:

@NamedNativeQueries ({
    @NamedNativeQuery (name = "select.distinct.sirm.for.customer.program", query = "select distinct(sirm.attribute) as attribute from store_item_received_material as sirm where sirm.store_item_id in (select si.id from store_item as si where si.customer_id = ? and si.program_id = ? and si.date_processed is not null)", resultClass=StoreItemReceivedMaterial.class)
})
@SqlResultSetMapping(name = "select.distinct.sirm.for.customer.program", entities=@EntityResult(entityClass = StoreItemReceivedMaterial.class))

但是这不起作用,因为该对象是一个实体对象,并且没有ID列。

那么,如何做到这一点的任何帮助

1 个答案:

答案 0 :(得分:0)

对于标量查询,您需要使用@ColumnResult进行结果集映射:

@NamedNativeQueries ({
    @NamedNativeQuery (name = "select.distinct.sirm.for.customer.program",
        query = "select distinct(sirm.attribute) as attribute from store_item_received_material as sirm where sirm.store_item_id in (select si.id from store_item as si where si.customer_id = ? and si.program_id = ? and si.date_processed is not null)", resultSetMapping = "select.distinct.sirm.for.customer.program" }) 

@SqlResultSetMapping(name = "select.distinct.sirm.for.customer.program",
    columns = @ColumnResult(name = "attribute"))