一、多查询条件无法整体接收问题的解决
在实际工作中,表单中所给出的查询条件有时是无法将其封装成一个对象,即查询方法只能携带多个参数,而不能携带将这多个参数进行封装的一个对象。对于这个问题,有两种解决方案:(1)根据Map查询;(2)使用索引号。
二、根据Map查询
1、修改Dao
import java.util.List;
import java.util.Map; import com.jmu.bean.Student; public interface IStudentDao {
// 根据条件查询问题
List<Student> selectStudentsByCondition(Map<String, Object> map);
}
com.jmu.dao.IStudentDao
2、修改Test
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.BasicConfigurator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.jmu.bean.Student;
import com.jmu.dao.IStudentDao;
import com.jmu.utils.MybatisUtils; public class MyTest {
private IStudentDao dao;
private SqlSession sqlSession; @Before
public void Before() {
sqlSession = MybatisUtils.getSqlSession();
dao = sqlSession.getMapper(IStudentDao.class);
BasicConfigurator.configure();
}
@After
public void after(){
if (sqlSession!=null) {
sqlSession.commit(); } } @Test
public void test08() {
Student stu = new Student("东东",21,95);
Map<String,Object> map=new HashMap<String,Object>();
map.put("nameCon", "小");
map.put("ageCon", 20);
map.put("stu", stu);
; List<Student> students = dao.selectStudentsByCondition(map);
for (Student student : students) {
System.out.println(student);
} } }
com.jmu.test.MyTest
3、修改map.xml
<mapper namespace="com.jmu.dao.IStudentDao">
<select id="selectStudentsByCondition" resultType="Student">
select id,name,age,score
from student
where name like '%' #{nameCon} '%'
and age >#{ageCon}
and score >#{stu.score} <!-- 也能放对象的属性 -->
</select>
</mapper>
mapper.xml
输出:
127 [main] DEBUG com.jmu.dao.IStudentDao.selectStudentsByCondition - <== Total: 1
Student [id=173, name=小明明, score=99.5, age=23]
三、使用索引号
在mapper.xml,#{ }中可以放的内容:
- 参数对象的属性
- 随意内容,此时的#{ }是个占位符
- 参数为map时的key
- 参数为map时,若key所对应的value为对象,即可将将对象的属性放入
- 参数的索引号
<mapper namespace="com.jmu.dao.IStudentDao">
<select id="selectStudentsByCondition" resultType="Student">
select id,name,age,score from student where name like '%' #{0} '%' and age > #{1} </select>
</mapper>
mapper.xml
import java.util.List;
import com.jmu.bean.Student; public interface IStudentDao {
// 根据条件查询问题
List<Student> selectStudentsByCondition(String name,int i);
}
IStudentDao
@Test
public void test08() { ; List<Student> students = dao.selectStudentsByCondition("明",20);
for (Student student : students) {
System.out.println(student);
} }
MyTest
输出:
Cause: org.apache.ibatis.binding.BindingException: Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]
失败,原因好像跟MyBatis的版本有关。
别人博客相关的截图