SQL参数映射
xml方式
<!--
parameterType属性用于限制接收参数类型,并且只能有一个parameterType属性
Java中所有包装类可使用MyBatis内置别名,其他类型需要使用全类名,
SQL中使用 #{} 方式使用传递来的参数,也可使用 ${} 方式但是有SQL注入风险
-->
<select id="selectById" parameterType="Integer" resultType="com.Student">
select * from students where stu_id = #{value} <!-- 对于单个参数,包裹内容任意内容可以是任意字符串-->
</select>
<select id="selectRange" parameterType="java.util.Map" resultType="com.Student">
select * from students where stu_id between #{min} and #{max} <!-- 对于多个参数,包裹内容是Map中的key-->
</select>
<select id="selectByEntity" parameterType="com.Student" resultType="com.Student">
select * from students where stu_id = #{stuId} <!-- 对于单个对象参数,包裹内容也可以是对象中的属性-->
</select>
用于测试的关键代码片段,sqlSession
为创建的SqlSession
对象,其他代码省略
/*单个参数*/
Student student = sqlSession.selectOne("student.selectById",1);
System.out.println(student); //输出结果
/*多个参数*/
HashMap<String, Object> param = new HashMap<>(); //map的值是Object时就可接收任意类型的值
param.put("min", 1);
param.put("max", 3);
List<Student> students = sqlSession.selectList("student.selectRange", param);
System.out.println(students); //输出结果
Student studentEntity = new Student();
studentEntity.setStuId(1);
student = sqlSession.selectOne("student.selectByEntity",studentEntity);
System.out.println(student); //输出结果
注解方式
package com;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface StudentMapper {
@Select("select * from students where stu_id = #{id}")
Student selectById(Integer id); //对于单个参数,会自动映射
@Select("select * from students where stu_id between #{min} and #{max}")
List<Student> selectRange(@Param("min") Integer min, @Param("max") Integer max); //对于多个参数,需使用@Param注解手动映射
@Select("select * from students where stu_id = #{stuId}")
Student selectByEntity(Student student); //对于单个对象参数,也可以自动映射对象中的属性
}
用于测试的关键代码片段,sqlSession
为创建的SqlSession
对象,其他代码省略
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
/*单个参数*/
Student student = mapper.selectById(1);
System.out.println(student); //输出结果
/*多个参数*/
List<Student> students = mapper.selectRange(1, 3);
System.out.println(students); //输出结果
/*单个对象*/
Student studentEntity = new Student();
studentEntity.setStuId(1);
student = mapper.selectByEntity(studentEntity);
System.out.println(student); //输出结果
Comments NOTHING