使用mybatis提供的动态sql可简化我们模糊查询时向sql追加各种条件,追加条件特别容易出错
dao接口:
List<User> selectAllUsersByCondition();
dao实现类:
@Override public List<User> selectAllUsersByCondition() { SqlSession sqlSession=null; List<User> userList = null; Map<String,String> map =new HashMap<String,String>(); map.put("uname", "奔"); try { userList = MyBatisUtils.getSqlSesion("mybatis/mybatis.xml").selectList("edu.aeon.mybatis.entity.UserMapper.selectAllUsersByCondition",map); } catch (IOException e) { e.printStackTrace(); } return userList; }
User.Mapper.xml:
<select id="selectAllUsersByCondition" parameterType="Map" resultType="User"> select uid,uname,upw from user <where> <if test="#{uname} !=null"> uname like concat('%',#{uname},'%') </if> </where> </select>
测试类:
public static void selectAllUsersByCondition(){ UserDao userDao =new UserDaoImpl(); List<User> userList = userDao.selectAllUsersByCondition(); for(User user:userList){ System.out.println(user); } }
测试结果: