请教!springboot @query自定义查询动态条件?

我有一个name条件 name不为空时执行 @Query("select * from a where 1=1 and name=?1",nativeQuery=true) 空时只执行select * from a where 1=1
怎么做,试了很多种方法都不行

这个spring boot和sping data jpa 有啥关系额,我用的jpa,看你这风格跟我的一样额

用@query是不好实现的,而且你这写的不通用,用jap的getBaseDao().findAll(getSpecification(spec));这个方法,拼接条件可以实现

这个sql比较复杂关联了5张表还有子查询,用jpa的方式实现不了,用自定义的好写一些

jpa的findall的getSpecification方法用public Predicate toPredicate(Root root,  
     CriteriaQuery query, CriteriaBuilder cb)拼接条件,就可以用代码控制了

我找到方法了,谢谢

找到什么方法呢?我正好也碰到这个问题

@Query(value = "select bill.id_ as id, bill.created_date as date, bill.no, lawyer_case .case_no as caseNo, " +
            "lawyer_case .case_name as caseName, customer.no as customerNo, customer.cn_name as customerName, " +
            "bill.total_expense_after_tax, bill.collected_money, bill.book_ticket_amount, bill.version " +
            "e1.name as creator, bill.status" +
            "from bill " +
            "left join lawyer_case on lawyer_case .case_no=bill.case_no " +
            "left join customer on customer.no=bill.customer_no " +
            "left join employee e1 on e1.id_=bill.creator " +
            "where IF (?1!='', customer_no=?1, 1=1) " +
            "and   IF (?2!='', case_no=?2, 1=1) " +
            "and   IF (?3!='', status=?3, 1=1) " +
            "and   IF (?4!='', creator'%',?4,'%')), 1=1) " +
            "and   create_by=?5 " +
            "ORDER BY ?#{#pageable} ",
            countQuery = "select count(*) " +
                    "from bill " +
                    "left join lawyer_case on lawyer_case .case_no=bill.case_no " +
                    "left join customer on customer.no=bill.customer_no " +
                    "left join employee e1 on e1.id_=bill.creator " +
                    "where IF (?1!='', customer_no=?1, 1=1) " +
                    "and   IF (?2!='', case_no=?2, 1=1) " +
                    "and   IF (?3!='', status=?3, 1=1) " +
                    "and   IF (?4!='', creator'%',?4,'%')), 1=1) " +
                    "and   create_by=?5 "+
                    "ORDER BY ?#{#pageable} ",
            nativeQuery = true)
    Page findAllBill(String customerNo, String caseNo, Integer status, String creator,
                               String createBy, Pageable pageable);

试一下这样写

您好,你的sql语句可以这样写:

@Query(value=“ select * from a where  name =?1 or -1=?1”,nativeQuery = true)

这样写就行了,让前端查询的时候,如果按照name查询,就传具体name的值,如果查询全部,就给你传 '-1' 即可!  我们的项目中
资源下载一直就是这样 写的.     你的sql语句肯定是不行的,数据库有个最左匹配原则,所以按照你的sql执行逻辑来看永远查的都是全部数据.

 

 

你可能感兴趣的:(请教!springboot @query自定义查询动态条件?)