简体   繁体   中英

Get aggregated query result in JPARepository

I am trying to fetch aggregated data from a JPARepository in my application. The SQL analogy would be something like:

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

The entity is:

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

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

    private Person.Sex sex;
    ...
}

and my JPARepository is:

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

The SQL approach does not return any result, why does it not, and are there non-SQL ways?

I am using Spring 1.4.0.RELEASE.

Thanks in advance!

EDIT: The SQL approach worked when I added persistence.xml configuration for JPA with the mapping of the class in question (Customer.class).

To get custom records from the domain or table we need to follow other approach. we can get the result using jdbcTemplate and bind it with dto using row mapper class.

For more detail please go through the link

The SQL approach worked when I added persistence.xml configuration for JPA with the mapping of the class in question (Customer.class). Otherwise the applicaiton did not recognise the table 'Customer' from the query.

The persistence.xml code is below:

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM