JPA NamedQuery 与聚合函数和分组依据一起使用
JPA NamedQuery use with aggregation functions and group by
我的数据库中有几条记录 table Foo,我需要聚合一列以求和它的值。
表示 table 的实体是这样的:
@Entity
@Table(name = "FOO")
@NamedQueries({
@NamedQuery(name = "Foo.total", query = "SELECT f.id, sum(f.someInt) AS
SOME_INT, f.parentId FROM Foo f where f.parentId = 'root' group by
p.parentId"),
@NamedQuery(name = "Foo.findAll", query = "SELECT f from Foo f") })
public class Foo {
@Id
@Column(name = "ID", insertable = false, updatable = false)
private String id;
@Column(name = "PARENT_ID", insertable = false, updatable = false)
private String parentId;
@Column(name = "SOME_INT", insertable = false, updatable = false)
private Integer someInt;
public Foo() {
}
}
如果我在我的 dao 服务 bean 上调用它:
entityManager.createNamedQuery("Foo.total", Foo.class).getResultList();
我收到这个错误:
Caused by: java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [Foo]
JPA 似乎无法将 return 值与对象 Foo 匹配。如果是这样,我怎样才能让它发挥作用?
如果我调用另一个@NamedQuery "Foo.findAll" 它工作正常。
我的数据库中有几条记录 table Foo,我需要聚合一列以求和它的值。
表示 table 的实体是这样的:
@Entity
@Table(name = "FOO")
@NamedQueries({
@NamedQuery(name = "Foo.total", query = "SELECT f.id, sum(f.someInt) AS
SOME_INT, f.parentId FROM Foo f where f.parentId = 'root' group by
p.parentId"),
@NamedQuery(name = "Foo.findAll", query = "SELECT f from Foo f") })
public class Foo {
@Id
@Column(name = "ID", insertable = false, updatable = false)
private String id;
@Column(name = "PARENT_ID", insertable = false, updatable = false)
private String parentId;
@Column(name = "SOME_INT", insertable = false, updatable = false)
private Integer someInt;
public Foo() {
}
}
如果我在我的 dao 服务 bean 上调用它:
entityManager.createNamedQuery("Foo.total", Foo.class).getResultList();
我收到这个错误:
Caused by: java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [Foo]
JPA 似乎无法将 return 值与对象 Foo 匹配。如果是这样,我怎样才能让它发挥作用?
如果我调用另一个@NamedQuery "Foo.findAll" 它工作正常。