zoukankan      html  css  js  c++  java
  • 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);

    如果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.

  • 相关阅读:
    [转]线程同步
    [转]C#线程同步(1)- 临界区&Lock
    获取系统空闲时间
    [转]一分钟明白 VS manifest 原理
    泛型总结
    wpf listbox touch 整个窗口移动
    git问题 next fetch will store in remotes/origin
    创建maven项目出现的问题
    JPA
    JDK JRE JVM
  • 原文地址:https://www.cnblogs.com/qq1141100952com/p/10916728.html
Copyright © 2011-2022 走看看