您的位置:首页 > 其它

[转]iBATIS查询条件为多个参数

2016-09-20 19:22 316 查看
原文:http://hi.baidu.com/wtx521/item/1ac70d0f1f518e8302ce1bad

当查询记录的时候,过滤记录的条件为多个的时候你就不能使用 parameterClass=int 等了,这个参数只能使用一次。

有两种解决方案:

1.使用对象构造查询参数

步骤:

a.改写student.xml

<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) {

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的定义,还就得就是 占位符一定要使用 ? 号

<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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iBatis