2016-08-15 48 views
0

我正尝试从我的应用程序中的JPARepository中获取聚合数据。在SQL比喻会是这样的:在JPARepository中获取聚合查询结果

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。

提前致谢!

编辑:当我添加JPA的persistence.xml配置与有问题的类(Customer.class)的映射时SQL方法工作。

回答

0

的SQL的方式,当我加入的persistence.xml配置JPA与类的问题的映射(Customer.class)工作。否则,应用程序不会从查询中识别“客户”表。

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> 

0

要从域或表中获取自定义记录,我们需要遵循其他方法。 我们可以使用jdbcTemplate获取结果,并使用行映射器类将其绑定到dto。

欲了解更多详情请到通过link