簡體   English   中英

在JPARepository中獲取匯總的查詢結果

[英]Get aggregated query result in JPARepository

我試圖從我的應用程序中的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方法起作用了。

要從域或表中獲取自定義記錄,我們需要遵循其他方法。 我們可以使用jdbcTemplate獲得結果,並使用行映射器類將其與dto綁定。

有關更多詳細信息,請通過鏈接

當我添加JPA的persistence.xml配置以及相關類(Customer.class)的映射時,SQL方法有效。 否則,應用程序無法從查詢中識別表“ Customer”。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM