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.

  • 相关阅读:
    Python——数据结构——字典
    Python——print()函数
    Python数据结构——序列总结
    elasticsearch全文检索java
    elasticsearch单例模式连接 java
    【转载】信号中断 与 慢系统调用
    设计模式——状态模式(C++实现)
    设计模式——观察者模式(C++实现)
    C++调用C方法
    设计模式——外观模式(C++实现)
  • 原文地址:https://www.cnblogs.com/qq1141100952com/p/10916728.html
Copyright © 2011-2022 走看看