当查询记录的时候,过滤记录的条件为多个的时候你就不能使用 parameterClass=int 等了,这个参数只能使用一次。
有两种解决方案:
1.使用对象构造查询参数
步骤:
a.改写student.xml
Java代码
<select id="selectStudentByIdAndName" resultClass="Student" parameterClass="Student">
select * from student where sid=#sid# and sname=#sname#
</select>
b.写实现
Java代码
public Student queryStudentsByNameAndId(Student student) {
Student s=null;
try {
s=(Student)sqlMapClient.queryForObject("selectStudentByIdAndName",student);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
c.测试
Java代码StudentDAO studentDAO=new StudentDAOImpl();
Student student=new Student();
student.setSid(326);
student.setSname("胡晓亮3");
Student s=studentDAO.queryStudentsByNameAndId(student);
log.info("score: "+s.getBirth());
d.结果
172 [main] INFO cn.com.xinli.ibatis.dao.impl.StudentDAOImpl(160) - score: 2009-06-17
2.使用map封装查询参数
a.改写student.xml,map 的定义一定要在sql的前面,第一次我做连写的时候就吧map的定义放在了后面,结果老是报错,说找不到map的定义,还就得就是 占位符一定要使用 ? 号
Java代码<parameterMap class="java.util.HashMap" id="parameterMap">
<parameter property="sid"/>
<parameter property="sname"/>
</parameterMap>
<select id="selectStudentByIdAndName" resultClass="Student" parameterMap="parameterMap">
select * from student where sid=? and sname=?
</select>
b.实现
Java代码public Student queryStudentsByNameAndId(HashMap<String,String> hashMap) {
Student s=null;
try { s=(Student)sqlMapClient.queryForObject("selectStudentByIdAndName",hashMap);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
return s;
}
c.测试
Java代码
StudentDAO studentDAO=new StudentDAOImpl();
HashMap m=new HashMap();
m.put("sname", "小虎");
m.put("sid", 12434);
Student s=studentDAO.queryStudentsByNameAndId(m);
log.info("score: "+s.getBirth());
d.结果
172 [main] INFO cn.com.xinli.ibatis.dao.impl.StudentDAOImpl(160) - score: 2009-06-17