Java小强个人技术博客站点    手机版
当前位置: 首页 >> 开源 >> SpringJPA底层DAO查询的写法归类总结

SpringJPA底层DAO查询的写法归类总结

150940 开源 | 2015-7-22

如果你要使用JPA就行底层操作,那么会涉及到很多查询的代码编写,虽然JPA屏蔽了复杂代码的编写,但是还是需要我们根据业务逻辑来编写一些额外的接口代码。

这里就来归纳总结下一些查询写法的编码示例。


HQL根据参数查询所有结果:

@Query("select t from Test t where t.userId =?1")
public List<Test> findAllByUserId(String userId);

语句中“?1”代表方法传来的第一个参数,你可以写多个参数。

如果根据该参数,查询你确定只有一行记录,可以把查询这样写:

@Query("select t from Test t where t.userId =?1 and rownum < 2")

为什么这样写?因为我碰到过某程序设计本该返回一行数据,但是由于程序BUG等因素,导致出现多条数据。

所以在查询时,每次都要从数据库返回大量数据,严重影响了数据库网络性能。所以我建议,有些事情,最好多做一步。


如果想执行联合查询,然后返回一个自定义对象,此时必须传分页参数Pageable

@Query("select a.createTime as createTime,b.id as id  from Testa a,Testb b " +
		" where a.id=b.id and t.level=?1 group by a.id " +
		" order by a.createTime asc, b.createTime asc")
public Page<TempObj> searchAllByLevel(int level,Pageable pageRequest);

TempObj就有两个字段createTime和id,对应as出来的查询字段。注意这里写的仍然是HQL

如果你想直接SQL来返回对象,注意对象和返回的列必须驼峰对应上才可以。

@Query(value="select * from t_test t where t.userId = ?1 and rownum < 2",nativeQuery = true)
public List<Test> findAllByUserId(String userId);

这个示例不是联合查询,但是可以看出,我并非执行HQL而是执行SQL来查询整个表,而Test是t_test的对应类,肯定的驼峰对应的。


统计类查询

@Query("select count(t) from Test t where t.userId = ?1")
public List<Long> findCountAllByUserId(String userId);

因为这里是Count,所以List第一个索引就是要获取的统计数量值。

@Query("select count(*) from Test t where t.userId = ?1")
public BigDecimal findCountAllByUserId(String userId);

或者你可以直接返回BigDecimal,因为你知道返回的是什么,所以上层使用时,可以直接判断统计量。

if(bigDecimal != null && bigDecimal.intValue() > 0) ;

如果是SUM类的统计,可以直接返回Long:

@Query("select sum(t.price) from Test t where t.userId = ?1")
public Long findSumAllByUserId(String userId);


执行原始SQL查询

@Query(value="select t.id as id,t.game_Name as gameName from t_test t where t.userId = ?1",nativeQuery = true)
public List<Object[]> findAllByName(String userId);

编写原始SQL,然后注解查询写nativeQuery = true,返回List,List中的Object数据根据索引获取对应的值。

如果你返回就是一个值,那可以不写成数组:

@Query(value="select max(t.price) from t_test t where t.userId = ?1",nativeQuery = true)
public List<Object> findMaxByName(String userId);


以上代码能满足日常基本查询的需求,可以参考。


114b456856f.jpg

推荐您阅读更多有关于“ spring jpa Query 联合查询 HQL nativeQuery ”的文章

上一篇:ORA-12560: TNS:protocol adapter error错误 下一篇:常用SpringJPA主键生成策略,UUID和自增

猜你喜欢

发表评论: