假日不打烊,JPA复杂查询方法

假日不打烊,JPA复杂查询方法

使用jpa的注解@Query进行复杂查询时,只需要注意两点即可

1,如果使用hql,请记住里面的代码是基于对象的

2,如果是使用原生的sql,需要使用nativeQuery = true,但是动态排序却不怎么好使。

 

使用原生sql查询,如果你返回的是一个对象,只需要注意返回的实体与对象一致性,如下面的例子

@Query(value = "select * from BLOG_POSTS t where t.id in (select tr.object_id from blog_term_relationships tr inner join blog_term_taxonomy tt on tr.term_taxonomy_id=tt.term_taxonomy_id where tt.term_id=?1)",
   countQuery="select count(*) from BLOG_POSTS t where t.id in (select tr.object_id from blog_term_relationships tr inner join blog_term_taxonomy tt on tr.term_taxonomy_id=tt.term_taxonomy_id where tt.term_id=?1)",
   nativeQuery = true)
Page<Posts> CusFindByTermsid(Long termsid,Pageable pageable);

使用HQL查询可以简化代码,如上面的sql查询采用同等的hql查询

 @Query("select p from posts p inner join p.term_relationships tr inner join tr.taxonomyid tt inner join tt.termid td where td.termid =?1")
 Page<Posts> CusFindByTermsid(Long termsid,Pageable pageable);

使用hql里面的字段信息均是对象,并不是数据库里面的字段,这点注意一下就OK了


爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情Blog Img