用户登录
用户注册

分享至

JPA动态拼接where条件

  • 作者: 尛灵厷主
  • 来源: 51数据库
  • 2021-07-28

在开发中,经常会涉及到动态拼接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则只返回对应的用户:

?

?

软件
前端设计
程序设计
Java相关