[英]Get two columns from @Query annotation having nativeQuery true 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.