JPA动态拼接where条件

在开发中,经常会涉及到动态拼接sql,以下就是JPA拼接条件案例:两种方法大同小异,只不过语法方面不同

mysql: 使用三元运算符的方式

    @Query(value = "select * from user a where if(?1 !='',id=?1 ,1=1  ) ",nativeQuery = true)
    public List<User> findPersonById(String id);

orcal:使用decode函数拼接

    @Query(value = "select * from prpsuser a where id=decode(?1 , null,id, ?1 ) ",nativeQuery = true)
    public List<User> findPersonById(String id);

写了一个简单的根据id查找用户的案例,首先不输入id,则返回所有数据,如下:

如果输入id则只返回对应的用户:

猜你喜欢

转载自blog.csdn.net/jungeCSND/article/details/106993922
今日推荐