Mybatis sql动态查询(可以填参数也可不填)

1.html

 <form action="datebaseServlet" method="post">
                        <input type="hidden" name="flag" value="1">
                        Seqname:<input type="text" name="seqname">
                        freeuse1:<input type="text" name="freeuse1">
                        <input type="submit">
                    </form>

2.servlet

  String sqename = request.getParameter("seqname");
            String  freeuse1 = request.getParameter("freeuse1");
            Datebase datebase =new Datebase();
            if(sqename!=null){
                datebase.setSeqname(sqename);
            }
            if(freeuse1!=null){
                datebase.setFreeuse1(freeuse1);
            }
          List <Datebase> list=  service.selectDatebaseLike(datebase);

3.service

 public List<Datebase> selectDatebaseLike(Datebase datebase) {
        DatebaseDAO dao = new DatebaseDAO();
        List<Datebase>  list  = dao.selectDatebaseLike(datebase);

        return list;
    }

4.dao

 public List<Datebase> selectDatebaseLike(Datebase datebase){
        SqlSession session = InitialSqlSession.openSqlSession();
        DatebaseMapper  mapper = session.getMapper(DatebaseMapper.class);
        List<Datebase> l =  mapper.selectDatebaseLike(datebase);
        session.close();
        return l;
    }

 

5.mapper

@SelectProvider(type= DatebaseSqlProvider.class,method="selectDatebaseLike")
    List<Datebase> selectDatebaseLike(Datebase datebase);

6.DatebaseSqlProvider

public class DatebaseSqlProvider {
    public String selectDatebaseLike(Datebase datebase) {
        return new SQL(){{

         SELECT("*");
         FROM("tb001");
         WHERE("1=1");
            if(!datebase.getSeqname().equals(""))
            {
                WHERE("tb001.seqname = #{seqname}");
            }
            if(!datebase.getFreeuse1().equals(""))
            {
                WHERE("tb001.freeuse1 = #{freeuse1}");
            }

        }}.toString();

    }
    public String select() {
        return new SQL(){{
            SELECT("*");
            FROM("tb001");
                WHERE("tb001.seqname = #{seqname}");

        }}.toString();

    }

}

WHERE1=1 使sql条件恒成立

 

posted @ 2020-07-11 12:42  When?  阅读(490)  评论(0编辑  收藏  举报