Mybatis 接口的单/多条件查询

规则

在MyBatis进行操作:

  • 如果操作方法只有一个简单类型或者字符串类型的参数,在Mapper配置中可以直接通过#{key}直接获取
  • 如果操作方法有一个对象类型的参数,在Mapper配置中可以直接通过#{attrName}获取对象的指定属性值(attrName必须是参数对象的属性)
  • 如果操作方法有一个Map类型的参数,在Mapper配置中可以直接通过#{key}获取key对应的value
  • 如果操作方法有多个参数:
    • 在mapper里使用特殊参数(arg0,arg1,arg2…)或(param1,param2,param3…),需要按顺序
    • 使用@Param(“start”)定义别名,在mapper中使用别名获取指定参数

DAO文件

Student queryStudentById(String stuNum);
int insertStudent(Student student);
List<Student> queryStudentListByPage(HashMap<String, Integer> map);
List<Student> queryStudentListByPage(int start, int length);
List<Student> queryStudentListByPage(@Param("sta") int start, @Param("len") int length);

mapper文件

mapper.xml 标签使用

<!-- 操作方法只有一个简单类型或者字符串类型的参数-->
<select id="queryStudentById" resultMap="map1">
    select <include refid="fieldAll" />
    from students
    where stu_num=#{stuNum}
</select>
<!-- 操作方法是一个对象类型的参数-->
<insert id="insertStudent" useGeneratedKeys="true" keyProperty="stuId">
    insert into students(stu_num, stu_name, stu_sex, stu_age)
    values(#{stuNum}, #{stuName}, #{stuSex}, #{stuAge})
</insert>
<!-- 操作方法是一个Map类型的参数-->
<select id="queryStudentListByPage" resultMap="map1">
    select <include refid="fieldAll" />
    from students
    limit #{start}, #{length}
</select>
<!-- 操作方法是多个参数-->
<select id="queryStudentListByPage" resultMap="map1">
	<!--
	select sid, stu_num, stu_name, stu_sex, stu_age
	from students
	limit #{arg0}, #{arg1}
	-->
	<!--
	select sid, stu_num, stu_name, stu_sex, stu_age
	from students
	limit #{param1}, #{param2}
	-->
    select <include refid="fieldAll" />
    from students
    limit #{sta}, #{len}
</select>

测试类

// Map类型的传参
public void queryStudentListByMap() {
    
    
	StudentDao studentDao = MyBatisUtil.getMapper(StudentDao.class);
	HashMap<String, Integer> map = new HashMap<String, Integer>();
	map.put("start", 0);
	map.put("length", 2);
	List<Student> students = studentDao.queryStudentListByPage(map);
}
// 多个参数
public void queryStudentListByPage() {
    
    
	StudentDao studentDao = MyBatisUtil.getMapper(StudentDao.class);
	List<Student> students = studentDao.queryStudentListByPage(1, 2);
}

猜你喜欢

转载自blog.csdn.net/weixin_55556204/article/details/125315148