SpringData JPA @Query动态SQL语句

前言

这次有个需求,需要动态的sql语句去查询,但是@Query正常情况下SQL语句是写死的,在查找了很多资料后,想到了一个好的解决办法

思路

利用MYSQL的判断来拼接SQL语句

实现

先上代码 

@Query(value = "select * from project_demand where project_id=?1 and if(?2!='',demand_id in (select demand_id from demand_user where user_id=?2),1=1)",nativeQuery = true)
List getListByUser(String projectId,String userId);
@Query(value = "select * from project_demand where project_id=?1 and if(?2!='',demand_id in (select demand_id from demand_user where user_id=?2),1=1)",nativeQuery = true)

红色部分,就是生成动态SQL的方法,利用MYSQL的if函数和我们传递的参数去进行判断,然后获取SQL语句。

你可能感兴趣的:(JAVA,SpringData,JPA)