利用mybatis的<where>标签是出了问题
下图是mabatis映射配置:
<select id="findStudents" resultType="com.sxk.data.Student">
select * from student
<where>
<if test="id != null">id = #{id},</if>
<if test="major != null">major = #{major}</if>
</where>
</select>下图是servlet代码:
@WebServlet(name = "SelectStudentServlet",urlPatterns = {"/selectStudent"})
public class SelectStudentServlet extends HttpServlet {
StudentDAO studentDAO = new StudentDAO();
List<Student> studentList;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (Objects.equals("/selectStudent", req.getServletPath())) {
String major = req.getParameter("major");
if ("".equals(major)) {
major = null;
}
Student student = new Student();
student.setMajor(major);
studentList = studentDAO.findStudentByStudent(student);
req.setAttribute("studentList", studentList);
req.getRequestDispatcher("/WEB-INF/show.jsp").forward(req,resp);
return;
}
}
}下图是dao代码:
public List<Student> findStudentByStudent(Student student) {
openSqlSession();
studentList = sqlSession.selectList("findStudents",student);
sqlSession.close();
return studentList;
}调试过程如下:



如图只要id为null,就报异常,但是我xml里面已经配置了<if test>标签的,假如去掉id一行,再调试:



同样major也设置为null,就没问题了,请老师解惑,是我<where>标签用错了嘛?因为课程里面没教,所以我是参照<set>设置的<where>.
正在回答
1、建议同学去掉id后边的,试试

2、如果同学写两条,建议在major前边写上and
<select id="findStudents" resultType="com.sxk.data.Student">
select * from student
<where>
<if test="id != null">id = #{id}</if>
<if test="major != null">and major = #{major}</if>
</where>
</select>
where 元素知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”或“OR”开头的,where 元素也知道如何将他们去除。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
- 参与学习 人
- 提交作业 277 份
- 解答问题 4297 个
Java数据库开发的必备技能,从流行的MySQL数据库开始,到Java原生的数据库管理接口JDBC的使用,再到常用的数据持久化框架MyBatis,让你向Java工程师的目标又迈进了一步!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星