1.需求
数据库中表字段很多 需要返回部分字段即可 同事sql语句比较复杂使用的原生sql @query进行的查询
2.代码实现
1 首先可以写一个接口
public interface GameSelectorSample {
/**
* 游戏id
* @return
*/
Integer getId();
/**
* 游戏名称
* @return
*/
String getName();
/**
* 创建时间
* @return
*/
Date getDtCreate();
}
这个接口会生成动态代理
2然后repository中语句就可以这样写 根据业务需求同事进行统计 这里删减部分字段啥的
@Query(value = "select g.id id,g.name name,g.min_playing minPlaying,g.dt_create dtCreate,g.dt_update dtUpdate, sum(gsctr.user) user,sum(gsctr.new_user) newUser,sum(gsctr.open) open,sum(gsctr.online) online,sum(gsctr.r1) r1,sum(gsctr.ex_user) exUser,sum(gsctr.ex_user_open) exUserOpen from game_sub_channel_total_report gsctr right join game g on (g.id=gsctr.game_id) " +
"where ( coalesce (?1 , null) is null or g.id in (?1) ) and ( coalesce (?2 , null) is null or g.category_id in (?2)) and if((?3!='' and ?4!=''), gsctr.dt between ?3 and ?4, 1=1) and " +
"( coalesce (?5 , null) is null or gsctr.sub_channel_id in (?5) ) group by g.id",
nativeQuery = true)
List<GameSelectorSample> searchGameSelector(List<Integer> gameIds, List<Integer> categories, String starTime, String endTime, List<String> subChannelIds);
3 最后这个因为是代理类所以我之后用了个处理转换为实体类同时进行了业务代码的计算什么的
3. 参考资料
学习Spring-Data-Jpa(十二)—投影Projections-对查询结果的扩展
SpringData JPA进阶查询—JPQL/原生SQL查询、分页处理、部分字段映射查询
官方文档Sort
官方文档Interface-based Projections