【问题标题】:Get aggregated query result in JPARepository在 JPARepository 中获取聚合查询结果
【发布时间】:2016-08-15 18:33:53
【问题描述】:

我正在尝试从我的应用程序中的 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 方法起作用了。

【问题讨论】:

    标签: java spring jpa


    【解决方案1】:

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

    更多详情请通过link

    【讨论】:

      【解决方案2】:

      当我使用相关类 (Customer.class) 的映射为 JPA 添加 persistence.xml 配置时,SQL 方法起作用了。否则,应用程序无法识别查询中的“客户”表。

      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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-24
        • 1970-01-01
        • 2021-07-26
        • 2014-10-22
        • 2018-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多