2016-08-15 137 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