Mybatis动态拼接sql

墨蓝 2022-06-15 05:25 1540阅读 0赞

Mybatis动态拼接sql
需求:查询某张表时条件不确定,可能有一个,可能有多个,也可能没有条件

  1. <!-- 动态sql -->
  2. <select id="fingUserList" parameterType="com.hl.myabtis.first.beas.UserQueryVo" resultType="com.hl.myabtis.first.beas.UserCustomer">
  3. select * from user
  4. <!-- where可以自动去掉条件中的第一个and -->
  5. <where>
  6. <if test="userCustomer!=null">
  7. <if test="userCustomer.sex!=null and userCustomer.sex!=''">
  8. and user.sex=#{userCustomer.sex}
  9. </if>
  10. <if test="userCustomer.address!=null and userCustomer.address!=''">
  11. and user.address like '$%{userCustomer.address}%'
  12. </if>
  13. </if>
  14. </where>

mapper接口:

  1. public List<UserCustomer> fingUserList(UserQueryVo userQueryVo) throws Exception;

测试:

  1. @Test
  2. public void findUserCount() throws Exception{
  3. SqlSession sqlSession = sqlSessionFactory.openSession();
  4. UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
  5. //构建一个包装类
  6. UserQueryVo userQueryVo = new UserQueryVo();
  7. //构建一个增强类
  8. UserCustomer userCustomer = new UserCustomer();
  9. userCustomer.setAddress("明月");
  10. userCustomer.setSex('1');
  11. //包装类包装这增强类作为查询条件
  12. userQueryVo.setUserCustomer(userCustomer);
  13. //不加任何条件
  14. int result = usermapper.findUserCount(null);
  15. System.out.println(result);
  16. sqlSession.close();
  17. }

发表评论

表情:
评论列表 (有 0 条评论,1540人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Mybatis动态拼接sql

    Mybatis动态拼接sql 需求:查询某张表时条件不确定,可能有一个,可能有多个,也可能没有条件 <!-- 动态sql --> <select id="