一、mapper标签:
<mapper namespace = "对应接口">
例如:<mapper namespace = "com.demo.dao.StudentDao">
二、查询语句 :
<select id="对应接口的方法名" parameterType = "传入参数类型" resultType="查询返回类型"</select>
例如:
<select id="selectStudentById" parameterType = "java.lang.Integer" resultType="com.demo.domain.Student">
select id,name from student where id = #{id}
</select>
三、parameterType
Mybatis框架可以通过反射,找到输入参数类型,一般可以省略
四、@Param注解(重点)
当需要传入多个参数时,可以使用@Param命名参数
例:
public List<Student> selectMulitParam(@Param("myname")String name,@Param(myage)Integer age)
<select id="selectMulitParam" resultType="com.demo.domain.Student">
select id,name,age from student where name = #{myname} and age = #{myage}
</select>
五、使用对象传参(重点)
<select id="selectMulitClassRoom" resultType="com.demo.domain.ClassRoom">
select id,name from classroom where studentName = #{与传入对象参数名相同} and studentAge = #{与传入对象参数名相同}
</select>
例:
class Student{
private String studentName;
private int studentAge;
......
}
public List<Student> selectMulitClassRoom(Student student)
<select id="selectMulitClassRoom" resultType="com.demo.domain.ClassRoom">
select id,name from classroom where studentName = #{studentName} and studentAge = #{studentAge}
</select>
六、按位置传参
例:
public List<Student> selectStudent(String name,Integer age)
<select id="selectStudent" resultType="com.demo.domain.Student">
select id,name,age from student where name = #{arg0} and age = #{arg1}
</select>
name,age ---->#{arg0},#{arg1}位置从左到右一一对应
七、map传参(不建议使用)
<select id="selectMultiByMap" resultType="com.demo.domain.Student">
select id,name,age from student where name = #{key} and age = #{key}
</select>
例:
List<Student>selectMultiByMap(Map<String.Object> map)
Map<String.Object> map = new HashMap<>();
map.put("myname","张三");
map.put("age",30);
<select id="selectMultiByMap" resultType="com.demo.domain.Student">
select id,name,age from student where name = #{myname} and age = #{age}
</select>
八、#和$的区别
1.#:占位符,告诉mybatis使用实际的参数值代替。并使用PrepareStatement对象执行sql语句,
#{...}代替sql语句的"?",这样子做更安全,更改迅速,通常也是首选做法。
2.$:字符串替换,告诉mybatis使用$包含的"字符串"替换所在位置。使用Statement把sql语句和${...}的内容连接起来,主要用在替换表名,列名,不同列排序等操作。