在Hibernate中使用查询映射实体 [英] Map entity using query in Hibernate
问题描述
考虑表格
销售额(id,seller_id,金额,日期)
以下是使用查询 SELECT从
sales
生成的视图seller_id,SUM(amount)FROM sales GROUP BY seller_id
total_sales(seller_id,金额)
我想为销售总额做一个实体,但没有sql方面的视图。
这个实体将从一个查询中构造出来。我发现的最接近的东西是 this a> ,但我无法完成工作。
即使我定义了加载器,hibernate也会查找实体的表并在出现错误时给出错误找到它。如果我创建表,它不会从我定义的命名查询中加载实体,Hibernate会自己生成查询。
有没有办法让@Loader工作或者有什么方法可以将查询映射到实体?
> new 在查询中? 选择新的TotalSales(seller_id,count(seller_id))
from sales
group by seller_id
您只需编写一个带构造函数的TotalSales类seller_id和一个整数。
编辑:使用标准API时,可以使用 AliasToBeanResultTransformer
(请参阅 API文档)。它将每个别名复制到同名的属性中。
List list = s.createCriteria(Sales.class)
.setProjection(Projections.projectionList()
.add(Projections.property(id),SellerId)
.add(Projections.rowCount(id),Count) )
.setResultTransformer(
new AliasToBeanResultTransformer(TotalSales.class))
.list();
然后你的 TotalSales
需要一个 SellerId
和 Count
属性。
consider table
sales (id, seller_id, amount, date)
and here is a view that is generated from sales
using query SELECT seller_id, SUM(amount) FROM sales GROUP BY seller_id
total_sales (seller_id, amount)
I want to make an entity for total sales but without the view on the sql side.
This entity will be constructed from a query. The closest thing I found is this, but I could not make it work.
Even if I define the loader, hibernate looks for the entity's table and gives an error if it cannot find it. If I create the table it does not load the entity from the named query I defined, Hibernate generates the query itself.
Is there a way to make @Loader to work or is there another way that I can map a query to entity?
Why don't you just use new
in the query?
select new TotalSales(seller_id, count(seller_id))
from sales
group by seller_id
You just write a class TotalSales with a constructor taking the seller_id and an integer.
Edit: When using criteria API, you can use the AliasToBeanResultTransformer
(See API docs). It copies every alias name to a property of the same name.
List list = s.createCriteria(Sales.class)
.setProjection(Projections.projectionList()
.add( Projections.property("id"), "SellerId" )
.add( Projections.rowCount("id"), "Count" ) )
.setResultTransformer(
new AliasToBeanResultTransformer(TotalSales.class) )
.list();
Then your TotalSales
needs a SellerId
and Count
property.
这篇关于在Hibernate中使用查询映射实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!