mybatis多参数类型解决方案
·
项目架构
案例代码
StudentDao
public interface StudentDao
{
// 多条件查询学生
Student selectOne2( Integer id, String name);
}
StudentDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace该mapper.xml唯一标识符 -->
<mapper namespace="com.stone.mybatis.mapper.StudentDao">
<!-- 多条件查询学生 arg1, arg0, param1, param2 -->
<select id="selectOne2" resultType="com.stone.mybatis.model.Student">
select * from student where id>#{id} and name=#{name}
</select>
</mapper>
测试
public class StudentTest
{
StudentDao mapper = null;
Reader reader = null;
SqlSessionFactory sessionFactory = null;
// 在每一次单元测试之前执行 (得到操作数据库对象)
@Before
public void bef() throws IOException
{
// 1. 加载mybatis配置文件
String resource = "mybatis-config.xml";
reader = Resources.getResourceAsReader(resource);
// 2.获取sqlsessionfactory
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
// 在每一次测试方法执行之后 (关闭操作数据库需要释放的资源)
@After
public void aft()
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
// 多条件查询
@Test
public void test6()
{
SqlSession sqlSession = sessionFactory.openSession();
mapper = sqlSession.getMapper(StudentDao.class);
Student student = mapper.selectOne2(2, "xw");
System.out.println(student);
}
}
运行结果
解决方案
根据错误提示,mybatis在多参数匹配时找不到参数,并且提示可用参数为[arg1, arg0, param1, param2]
解决方案一 :将mapper中的参数替换为arg0 ,arg1…
解决方案二: 将mapper中的参数替换为param1,param2…
方案三:使用@Param注解指定传入参数

方案四:利用pojo封装对象,传入参数为pojo属性名
pojo
package com.stone.mybatis.model;
public class Student
{
private Integer id; // 学生学号
private String name; // 学生姓名
private Integer age; // 学生年龄
private String sex; // 学生性别
public Student()
{
}
public Student(Integer id, String name, Integer age, String sex)
{
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Integer getAge()
{
return age;
}
public void setAge(Integer age)
{
this.age = age;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
@Override
public String toString()
{
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
mapper接口
mapper xml

方案五:传入map集合,添加map的key就是参数名
mapper接口
mapper xml
测试代码
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)