我有一个实体类,它的服务和存储库如下:
@Entity
@Table(name = "user")
public class User implements Serializable{
@Id
@Column(name = "id", unique = true)
private String userId;
@Column(name = "user_name")
private String userName;
@Column(name = "emp_code")
private String empCode;
// ... other properties
}
存储库
@Repository
public interface UserRepository extends PagingAndSortingRepository<User, String>
{
// .... working
@Query("select u.userName from User u")
Page<User> findAllUserName(Pageable pageable);
//... not working
@Query("select u.userName, u.empCode from User u")
Page<User> findAllUserNameAndEmpCode(Pageable pageable);
}
当我尝试执行findAllUserName
时,它可以正常运行。但是当使用findAllUserNameAndEmpCode
时,它会在启动tomcat时抛出异常 :
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting CLOSE, found ',' near line 1, column 29 [select count(u.userName,u.empCode) from com.entity.User u]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:79)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:138)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)
... 63 more
我不知道为什么,以及它如何将此查询转换为SELECT count(..)
? expecting CLOSE, found ','
的含义是什么?
请帮忙..谢谢
答案 0 :(得分:6)
您应该指定计数查询。 select函数的Page返回值需要知道将有多少结果。因此,它会发送一个COUNT查询,该查询可能来自您的选择查询,如下所示:
select count(u.userName,u.empCode) from com.entity.User u
这是错误的,因为COUNT函数只接受一个参数。所以你应该创建自定义计数查询(可能是这样的):
select count(u.userName) from com.entity.User u
并将其放入@Query
注释:
@Query(
value = "select u.userName, u.empCode from User u",
countQuery = "select count(u.userName) from com.entity.User u"
)
Page<User> findAllUserNameAndEmpCode(Pageable pageable);