目录
1.collection /** * 通过id查询老师信息及老师的学生,通过collection标签处理映射关系 * @param id * @return */
Teacher getTeacherAndStudent(@Param("id") int id);
1.MyBatis获取参数值的两种方式
MyBatis获取参数值的两种方式:${}和#{}
${}的本质就是字符串拼接,#{}的本质就是占位符赋值
${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;
但是#{}使用用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号
1、单个字面量类型的参数
若 mapper 接口中的方法参数为单个的字面量类型此时可以使用 ${} 和 #{} 以任意的名称获取参数的值,注意 ${} 需要手动加单引号2 、多个字面量类型的参数若 mapper 接口中的方法参数为多个时此时 MyBatis 会自动将这些参数放在一个 map 集合中,以 arg0,arg1... 为键,以参数为值;以param1,param2... 为键,以参数为值;因此只需要通过 ${} 和 #{} 访问 map 集合的键就可以获取相对应的值,注意${} 需要手动加单引号3 、 map 集合类型的参数若 mapper 接口中的方法需要的参数为多个时,此时可以手动创建 map 集合,将这些数据放在 map 中只需要通过 ${} 和 #{} 访问 map 集合的键就可以获取相对应的值,注意 ${} 需要手动加单引号4 、实体类类型的参数若 mapper 接口中的方法参数为实体类对象时此时可以使用 ${} 和 #{} ,通过访问实体类对象中的属性名获取属性值,注意 ${} 需要手动加单引号5 、使用 @Param 标识参数可以通过 @Param 注解标识 mapper 接口中的方法参数此时,会将这些参数放在 map 集合中,以 @Param 注解的 value 属性值为键,以参数为值;以param1,param2... 为键,以参数为值;只需要通过 ${} 和 #{} 访问 map 集合的键就可以获取相对应的值,注意 ${} 需要手动加单引号
2. MyBatis的各种查询
1 、查询一个实体类对象/*** 根据用户 id 查询用户信息* @param id* @return*/User getUserById ( @Param ( "id" ) int id );<select id = "getUserById" resultType = "User" >select * from t_user where id = #{id}</select>2 、查询一个 list 集合/*** 查询所有用户信息* @return*/List < User > getUserList ();<select id = "getUserList" resultType = "User" >select * from t_user</select>3 、查询单个数据/*** 查询用户的总记录数* @return* 在 MyBatis 中,对于 Java 中常用的类型都设置了类型别名* 例如: java.lang.Integer-->int|integer* 例如: int-->_int|_integer* 例如: Map-->map,List-->list*/int getCount ();<select id = "getCount" resultType = "_integer" >select count(id) from t_user</select>4 、查询一条数据为 map 集合/*** 根据用户 id 查询用户信息为 map 集合* @param id* @return*/Map < String , Object > getUserToMap ( @Param ( "id" ) int id );<select id = "getUserToMap" resultType = "map" >select * from t_user where id = #{id}</select>5 、查询多条数据为 map 集合方式一:/*** 查询所有用户信息为 map 集合* @return* 将表中的数据以 map 集合的方式查询,一条数据对应一个 map ;若有多条数据,就会产生多个 map 集合,此时可以将这些 map 放在一个 list 集合中获取*/List < Map < String , Object >> getAllUserToMap ();<select id = "getAllUserToMap" resultType = "map" >select * from t_user</select>方式二:/*** 查询所有用户信息为 map 集合* @return* 将表中的数据以 map 集合的方式查询,一条数据对应一个 map ;若有多条数据,就会产生多个 map 集合,并且最终要以一个 map 的方式返回数据,此时需要通过 @MapKey 注解设置 map 集合的键,值是每条数据所对应的map 集合*/@MapKey ( "id" )Map < String , Object > getAllUserToMap ();<select id = "getAllUserToMap" resultType = "map" >select * from t_user</select>结果:<!--{1={password=123456, sex= 男 , id=1, age=23, username=admin},2={password=123456, sex= 男 , id=2, age=23, username= 张三 },3={password=123456, sex= 男 , id=3, age=23, username= 张三 }}-->
3.特殊SQL的执行
1、模糊查询
/*** 测试模糊查询* @param mohu* @return*/List < User > testMohu ( @Param ( "mohu" ) String mohu );<select id = "testMohu" resultType = "User" ><!--select * from t_user where username like '%${mohu}%'--><!--select * from t_user where username like concat('%',#{mohu},'%')-->select * from t_user where username like "%"#{mohu}"%"</select>或者是<select id="testMohu" resultType="User">
<bind name="mohu" value="'%' +mohu+ '%'"/>
select * from t_user where username like #{mohu}
</select>
2、批量删除
/*** 批量删除* @param ids* @return*/int deleteMore ( @Param ( "ids" ) String ids );<delete id = "deleteMore" >delete from t_user where id in (${ids})</delete>3、动态设置表名
/*** 动态设置表名,查询所有的用户信息* @param tableName* @return*/List < User > getAllUser ( @Param ( "tableName" ) String tableName );<select id = "getAllUser" resultType = "User" >select * from ${tableName}</select>4、添加功能获取自增的主键
t_clazz(clazz_id,clazz_name)t_student(student_id,student_name,clazz_id)1 、添加班级信息2 、获取新添加的班级的 id3 、为班级分配学生,即将某学的班级 id 修改为新添加的班级的 id/*** 添加用户信息* @param user* @return* useGeneratedKeys :设置使用自增的主键* keyProperty :因为增删改有统一的返回值是受影响的行数,因此只能将获取的自增的主键放在传输的参数 user 对象的某个属性中*/int insertUser ( User user );<insert id = "insertUser" useGeneratedKeys = "true" keyProperty = "id" >insert into t_user values(null,#{username},#{password},#{age},#{sex})</insert>
4.自定义映射resultMap
1、resultMap处理字段和属性的映射关系
若字段名和实体类中的属性名不一致,则可以通过 resultMap 设置自定义映射<!--resultMap :设置自定义映射属性:id :表示自定义映射的唯一标识type :查询的数据要映射的实体类的类型子标签:id :设置主键的映射关系result :设置普通字段的映射关系association :设置多对一的映射关系collection :设置一对多的映射关系属性:property :设置映射关系中实体类中的属性名column :设置映射关系中表中的字段名--><resultMap id = "userMap" type = "User" ><id property = "id" column = "id" ></id><result property = "userName" column = "user_name" ></result><result property = "password" column = "password" ></result><result property = "age" column = "age" ></result><result property = "sex" column = "sex" ></result></resultMap><!--List<User> testMohu(@Param("mohu") String mohu);--><select id = "testMohu" resultMap = "userMap" ><!--select * from t_user where username like '%${mohu}%'-->select id,user_name,password,age,sex from t_user where user_name likeconcat('%',#{mohu},'%')</select>若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用 _ ),实体类中的属性名符合 Java 的规则(使用驼峰)此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系a> 可以通过为字段起别名的方式,保证和实体类中的属性名保持一致b> 可以在 MyBatis 的核心配置文件中设置一个全局配置信息 mapUnderscoreToCamelCase ,可以在查询表中数据时,自动将 _ 类型的字段名转换为驼峰例如:字段名 user_name ,设置了 mapUnderscoreToCamelCase ,此时字段名就会转换为userName
2、多对一映射处理
#创建教师表
CREATE TABLE `teacher` (
`id` int(10) NOT NULL,
`name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#创建学生表
CREATE TABLE `student` (
`id` int(10) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`tid` int(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
对应的实体类
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private Integer id;
private String name;
private List<Student> studentList;
}
import lombok.Data;
@Data
public class Student {
private Integer id;
private String name;
private Integer tid;
private String teacherName;
private Teacher teacher;
}
1.级联方式处理映射关系
** * 查询学生及学生关联的老师,通过级联方式处理映射关系 * @param id * @return */ Student getStudentById(@Param("id") Integer id);<select id="getStudentById" resultType="chen.pojo.Student"> select s.id,s.`name`,s.tid,t.`name` as teacher_name from student s left join teacher t on t.id= s.tid where s.id=#{id} </select>打印结果--->
==> Preparing: select s.id,s.`name`,s.tid,t.`name` as teacher_name from student s left join teacher t on t.id= s.tid where s.id=?
==> Parameters: 1(Integer)
<== Columns: id, name, tid, teacher_name
<== Row: 1, 小明, 1, 秦老师
<== Total: 1
Student(id=1, name=小明, tid=1, teacherName=秦老师, teacher=null)2.>使用association处理映射关系
/** * 查询学生及学生关联的老师,通过使用association处理映射关系 * @param id * @return */ Student getStudentAndTeacherById(@Param("id") Integer id);<resultMap id="StudentAndTeacherById" type="chen.pojo.Student"> <id column="id" property="id"></id> <result column="name" property="name"></result> <association property="teacher" javaType="chen.pojo.Teacher"> <id property="id" column="tid"></id> <result property="name" column="teacher_name"></result> </association> </resultMap> <select id="getStudentAndTeacherById" resultMap="StudentAndTeacherById"> select s.id,s.`name`,s.tid,t.`name` as teacher_name from student s left join teacher t on t.id= s.tid where s.id=#{id} </select>打印结果----->
==> Preparing: select s.id,s.`name`,s.tid,t.`name` as teacher_name from student s left join teacher t on t.id= s.tid where s.id=?
==> Parameters: 1(Integer)
<== Columns: id, name, tid, teacher_name
<== Row: 1, 小明, 1, 秦老师
<== Total: 1
Student(id=1, name=小明, tid=null, teacherName=null, teacher=Teacher(id=1, name=秦老师, studentList=null))
3.分步查询
/** * 查询学生及学生关联的老师,通过使用分步查询 * @param id * @return */ Student getStudentAndTeacherByByStep(Integer id);<select id="getStudentAndTeacherByByStep" resultMap="StudentAndTeacherByByStep"> select s.id,s.`name`,s.tid from student s where id=#{id} </select><resultMap id="StudentAndTeacherByByStep" type="chen.pojo.Student"> <id column="id" property="id"></id> <result column="name" property="name"></result> <!-- select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId) column:将sql以及查询结果中的某个字段设置为分步查询的条件 --> <association property="teacher" select="chen.dao.TeacherMapper.getTeacherById" column="tid" > </association> </resultMap>package chen.dao; @Mapper public interface TeacherMapper { /** * 通过分步查询-->id查询老师信息 * @param id * @return */ Teacher getTeacherById(@Param("id") int id); }
<select id="getTeacherById" resultType="chen.pojo.Teacher"> select t.id,t.name from teacher t where id=#{id} </select>查询结果--------->
==> Preparing: select s.id,s.`name`,s.tid from student s where id=?
==> Parameters: 1(Integer)
<== Columns: id, name, tid
<== Row: 1, 小明, 1
====> Preparing: select t.id,t.name from teacher t where id=?
====> Parameters: 1(Integer)
<==== Columns: id, name
<==== Row: 1, 秦老师
<==== Total: 1
<== Total: 1
Student(id=1, name=小明, tid=null, teacherName=null, teacher=Teacher(id=1, name=秦老师, studentList=null))
3.一对多映射处理
1.collection
/**
* 通过id查询老师信息及老师的学生,通过collection标签处理映射关系
* @param id
* @return
*/Teacher getTeacherAndStudent(@Param("id") int id);
<select id="getTeacherAndStudent" resultMap="TeacherAndStudent"> select s.id student_id,s.`name` student_name,s.tid,t.`name`,t.id from teacher t left join student s on t.id= s.tid where t.id=#{id} </select> <resultMap id="TeacherAndStudent" type="chen.pojo.Teacher"> <id column="id" property="id"></id> <result column="name" property="name"></result><!--ofType :设置 collection 标签所处理的集合属性中存储数据的类型--><collection property="studentList" ofType="chen.pojo.Student"> <id property="id" column="student_id"></id> <result property="name" column="student_name"></result> <result property="tid" column="tid"></result> </collection> </resultMap>打印结果---------->
==> Preparing: select s.id student_id,s.`name` student_name,s.tid,t.`name`,t.id from teacher t left join student s on t.id= s.tid where t.id=?
==> Parameters: 1(Integer)
<== Columns: student_id, student_name, tid, name, id
<== Row: 1, 小明, 1, 秦老师, 1
<== Row: 2, 小红, 1, 秦老师, 1
<== Row: 3, 小张, 1, 秦老师, 1
<== Row: 4, 小李, 1, 秦老师, 1
<== Row: 5, 小王, 1, 秦老师, 1
<== Total: 5
Teacher(id=1, name=秦老师, studentList=[Student(id=1, name=小明, tid=1, teacherName=null, teacher=null), Student(id=2, name=小红, tid=1, teacherName=null, teacher=null), Student(id=3, name=小张, tid=1, teacherName=null, teacher=null), Student(id=4, name=小李, tid=1, teacherName=null, teacher=null), Student(id=5, name=小王, tid=1, teacherName=null, teacher=null)])2.分步查询
/** * 通过id查询老师信息及老师的学生,通过collection标签处理映射关系 * @param id * @return */ Teacher getTeacherAndStudentByStep(@Param("id") int id);<select id="getTeacherAndStudentByStep" resultMap="TeacherAndStudentByStep"> select t.`name`,t.id from teacher t where t.id=#{id} </select> <resultMap id="TeacherAndStudentByStep" type="chen.pojo.Teacher"> <id column="id" property="id"></id> <result column="name" property="name"></result> <collection property="studentList" select="chen.dao.StudentMapper.getStudentByTid" column="id"> <id column="id" property="id"></id> <result column="name" property="name"></result> </collection> </resultMap>package chen.dao; @Mapper public interface StudentMapper {/** * 查询学生通过关联的老师id * @param tid * @return */ Student getStudentByTid(@Param("tid") Integer tid);}
<select id="getStudentByTid" resultType="chen.pojo.Student"> select s.id,s.`name`,s.tid from student s where tid=#{tid} </select>打印结果-------------->
==> Preparing: select t.`name`,t.id from teacher t where t.id=?
==> Parameters: 1(Integer)
<== Columns: name, id
<== Row: 秦老师, 1
====> Preparing: select s.id,s.`name`,s.tid from student s where tid=?
====> Parameters: 1(Integer)
<==== Columns: id, name, tid
<==== Row: 1, 小明, 1
<==== Row: 2, 小红, 1
<==== Row: 3, 小张, 1
<==== Row: 4, 小李, 1
<==== Row: 5, 小王, 1
<==== Total: 5
<== Total: 1
Teacher(id=1, name=秦老师, studentList=[Student(id=1, name=小明, tid=1, teacherName=null, teacher=null), Student(id=2, name=小红, tid=1, teacherName=null, teacher=null), Student(id=3, name=小张, tid=1, teacherName=null, teacher=null), Student(id=4, name=小李, tid=1, teacherName=null, teacher=null), Student(id=5, name=小王, tid=1, teacherName=null, teacher=null)])
分步查询的优点
分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:lazyLoadingEnabled :延迟加载的全局开关。当开启时,所有关联对象都会延迟加载aggressiveLazyLoading :当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载此时就可以实现按需加载,获取的数据是什么,就只会执行相应的 sql 。此时可通过 association 和collection 中的 fetchType 属性设置当前的分步查询是否使用延迟加载, fetchType="lazy( 延迟加载 )|eager( 立即加载 )"
5.动态SQL
1、if
if 标签可通过 test 属性的表达式进行判断,若表达式的结果为 true ,则标签中的内容会执行;反之标签中 的内容不会执行
<!--List<Emp> getEmpListByMoreTJ(Emp emp);-->
<select id="getEmpListByMoreTJ" resultType="Emp">
select * from t_emp where 1=1
<if test="ename != '' and ename != null">
and ename = #{ename}
</if>
<if test="age != '' and age != null">
and age = #{age}
</if>
<if test="sex != '' and sex != null">
and sex = #{sex}
</if>
</select>
2、where
<select id="getEmpListByMoreTJ2" resultType="Emp">
select * from t_emp
<where>
<if test="ename != '' and ename != null">
ename = #{ename}
</if>
<if test="age != '' and age != null">
and age = #{age}
</if>
<if test="sex != '' and sex != null">
and sex = #{sex}
</if>
</where>
</select>
where 和 if 一般结合使用:a> 若 where 标签中的 if 条件都不满足,则 where 标签没有任何功能,即不会添加 where 关键字b> 若 where 标签中的 if 条件满足,则 where 标签会自动添加 where 关键字,并将条件最前方多余的and 去掉注意: where 标签不能去掉条件最后多余的 and
3、trim
trim 用于去掉或添加标签中的内容常用属性:prefix :在 trim 标签中的内容的前面添加某些内容prefixOverrides :在 trim 标签中的内容的前面去掉某些内容suffix :在 trim 标签中的内容的后面添加某些内容suffixOverrides :在 trim 标签中的内容的后面去掉某些内容
<select id="getEmpListByMoreTJ" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and">
<if test="ename != '' and ename != null">
ename = #{ename} and
</if>
<if test="age != '' and age != null">
age = #{age} and
</if>
<if test="sex != '' and sex != null">
sex = #{sex}
</if>
</trim>
</select>
4、choose、when、otherwise
choose 、 when 、 otherwise 相当于 if...else if..else
<!--List<Emp> getEmpListByChoose(Emp emp);-->
<select id="getEmpListByChoose" resultType="Emp">
select <include refid="empColumns"></include> from t_emp
<where>
<choose>
<when test="ename != '' and ename != null">
ename = #{ename}
</when>
<when test="age != '' and age != null">
age = #{age}
</when>
<when test="sex != '' and sex != null">
sex = #{sex}
</when>
<when test="email != '' and email != null">
email = #{email}
</when>
</choose>
</where>
</select>
5、foreach
属性:collection :设置要循环的数组或集合item :表示集合或数组中的每一个数据separator :设置循环体之间的分隔符open :设置 foreach 标签中的内容的开始符close :设置 foreach 标签中的内容的结束符
<!--int insertMoreEmp(List<Emp> emps);-->
<insert id="insertMoreEmp">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null,#{emp.ename},#{emp.age},#{emp.sex},#{emp.email},null)
</foreach>
</insert>
<!--int deleteMoreByArray(int[] eids);-->
<delete id="deleteMoreByArray">
delete from t_emp where
<foreach collection="eids" item="eid" separator="or">
eid = #{eid}
</foreach>
</delete>
<!--int deleteMoreByArray(int[] eids);-->
<delete id="deleteMoreByArray">
delete from t_emp where eid in
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
6.SQL片段
sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入
<sql id="empColumns">
eid,ename,age,sex,did
</sql>
select <include refid="empColumns"></include> from t_emp