2016-08-15 10 views
0

私のアプリケーションのJPARepositoryから集計データを取得しようとしています。JPARepositoryで集約クエリ結果を取得

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

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

    private Person.Sex sex; 
    ... 
} 

と私のJPARepositoryは次のとおりです:エンティティである

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

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のアナロジーは次のようなものになるだろうそうではなく、SQL以外の方法がありますか?

私はSpring 1.4.0.RELEASEを使用しています。

ありがとうございます!

EDIT:SQLのアプローチは、問題のクラス(Customer.class)のマッピングを使用してJPAのpersistence.xml構成を追加したときに機能しました。

答えて

0

を通過してください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> 

0

ドメインまたはテーブルからカスタムレコードを取得するには、他の方法に従う必要があります。 jdbcTemplateを使用して結果を取得し、行マッパークラスを使用してdtoにバインドできます。私は問題のクラスのマッピング(Customer.class)とJPAのためのpersistence.xmlの設定を追加する際の詳細については

link