Hibernate 之 @Query查询

注解  @Query 允许在方法上使用 JPQL。 列如:

@Query("select u from User u where u.name=?1 and u.department_id=?2")

public User findUser(String name,Integer departmentId);

如果是使用SQL,而不是JPSQL,可以使用 @Query 的 nativeQuery属性,设置为true:例如

@Query(value="select * from user  where name=?1 and department_id=?2",nativeQuery=true)

public User findUser(String name,Integer departmentId);

还有一种情况是:无论是JPQL还是 SQL,都支持 ‘命名参数’

@Query(value="select * from user  where name=:name and department_id=:departmentId",nativeQuery=true)

public User findUser(String name,Integer departmentId);

扫描二维码关注公众号,回复: 6268978 查看本文章

如果SQL 或者 JPQL查询的结果集并非 Entity,可以使用Object[]数组代替,比如分组统计每个部分的用户数

@Query(value="select department_id ,count(*) from user group by depatment_id",nativeQuery=true)

public List<Object[]> queryUserCount();

这条查询语句返回数组,对象类型依赖查询结果,本例子中,返回的是String 和 BigInteger 类型

注意:Spring Data 没有像BeetlSQL那样允许将SQL查询结果映射到一个任意的POJO或者 Map 对象上,因此,对于这种 非实体返回结果,只能使用 Object[] 数组,数组中每个元素的类型要小心处理。 比如count(*) 返回的是BigInteger。在不同的数据库中,返回的可能是BigDecimal.

猜你喜欢

转载自www.cnblogs.com/qq1141100952com/p/10916728.html