[英]Get aggregated query result in JPARepository
I am trying to fetch aggregated data from a JPARepository in my application. 我试图从我的应用程序中的JPARepository中获取聚合数据。 The SQL analogy would be something like: SQL类比是这样的:
SELECT c.sex as Sex, count(c.sex) as Count
FROM customer c
GROUP BY c.sex
The entity is: 实体为:
@Entity(name = "customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Person.Sex sex;
...
}
and my JPARepository is: 而我的JPARepository是:
public interface CustomerRepository extends JpaRepository<Customer, Long> {
@Query(value = "SELECT c.sex as Sex, count(c.sex) as Count FROM customer c")
List<Object[]> countBySex();
}
The SQL approach does not return any result, why does it not, and are there non-SQL ways? SQL方法不返回任何结果,为什么不返回结果,并且有非SQL方法吗?
I am using Spring 1.4.0.RELEASE. 我正在使用Spring 1.4.0.RELEASE。
Thanks in advance! 提前致谢!
EDIT: The SQL approach worked when I added persistence.xml configuration for JPA with the mapping of the class in question (Customer.class). 编辑:当我为有关问题的类(Customer.class)的映射为JPA添加persistence.xml配置时,SQL方法起作用了。
The SQL approach worked when I added persistence.xml configuration for JPA with the mapping of the class in question (Customer.class). 当我添加JPA的persistence.xml配置以及相关类(Customer.class)的映射时,SQL方法有效。 Otherwise the applicaiton did not recognise the table 'Customer' from the query. 否则,应用程序无法从查询中识别表“ Customer”。
The persistence.xml code is below: persistence.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="jpa.sample.plain">
<class>net.datamanager.application.Customer</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:spring" />
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.