在JPARepository中获取聚合查询结果

时间:2016-08-15 18:33:53

标签: java spring jpa

我正在尝试从我的应用程序中的JPARepository获取聚合数据。 SQL类比如下:

SELECT c.sex as Sex, count(c.sex) as Count 
FROM customer c
GROUP BY c.sex

该实体是:

@Entity(name = "customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private Person.Sex sex;
    ...
}

我的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();
}

SQL方法不返回任何结果,为什么不返回,是否存在非SQL方式?

我正在使用Spring 1.4.0.RELEASE。

提前致谢!

编辑:当我使用相关类的映射(Customer.class)为JPA添加persistence.xml配置时,SQL方法有效。

1 个答案:

答案 0 :(得分:0)

当我使用相关类的映射(Customer.class)为JPA添加persistence.xml配置时,SQL方法有效。否则,应用程序无法从查询中识别出“客户”表。

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>