目录
1. MyBatis获取参数值的方式
1.1 MyBatis获取参数值的两种方式:${}和#{}
${}的本质就是字符串拼接,#{}的本质就是占位符赋值
${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;
但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时, 可以自动添加单引号
注: 建议使用#{} 的格式, ${} 格式需要拼接,比较麻烦
<!--
三种写法
1.[字符串形式]拼接(这里的${id}参数不能是字符串)
where id = ${id}
2.参数是[字符串]的要加上单引号
where id = '${id}'
3.问号?占位符
where id = #{id}
-->
1.2 参数获取的例子 (特别注意Map形式的参数)
<!--
五种常见写法:
1.参数是(String username, String password)
where username = #{arg0}
and password = #{arg1}
2.参数是(String username, String password)
where username = #{param1}
and password = #{param2}
3.使用@Param注解(@Param("username") String username, @Param("password") String password)
where username = #{username}
and password = #{password}
4.参数使用Map集合(Map map)
where username = #{username}
and password = #{password}
注: 在方法上不加@MapKey注解会出现红色的警告线,这个可以不用管
实在不舒服的话,加上也可以, 但是加上@MapKey注解之后的效果会与不加之前的不一样
5.实体类类型的参数 (User为例)
where username = #{username}
and password = #{password}
-->
第4点 Map集合 举个例子说明:
在usermapper接口中定义getUserToMap方法:
1.没有加注解
注: 没有注解会有红色的警告线,但没有任何的错误
结果:
2.加上注解
结果:
总结:
加上@@MapKey注解后,会再嵌套一次Map,把@MapKey("id")里的id作为键,查询的结果作为值,封装的新的Map集合中
2. MyBatis的各种查询功能
2.1 查询一个实体类对象
/**
*根据用户id查询用户信息
*@param id
*@return
*/
User getUserById(@Param("id") int id);
<!--User getUserById(@Param("id") int id);-->
<select id="getUserById" resultType="User"> select * from t_user where id = #{id}
</select>
2.2 查询一个list集合
/**
*查询所有用户信息
*@return
*/
List<User> getUserList();
<!--List<User> getUserList();-->
<select id="getUserList" resultType="User"> select * from t_user
</select>
当查询的数据为多条时,不能使用实体类作为返回值,否则会抛出异常
TooManyResultsException;但是若查询的数据只有一条,可以使用实体类或集合作为返回值. 即查询的数据为多条时,返回值的类型是List
2.3 查询单个数据
/**
*查询用户的总记录数
*@return
*在MyBatis中,对于Java中常用的类型都设置了类型别名
*例如: java.lang.Integer-->int|integer
*例如: int-->_int|_integer
*例如: Map-->map,List-->list
*/
int getCount();
<!--int getCount();-->
<select id="getCount" resultType="_integer"> select count(id) from t_user
</select>
2.4 查询一条数据为map集合
/**
*根据用户id查询用户信息为map集合
*@param id
*@return
*/
Map<String, Object> getUserToMap(@Param("id") int id);
<!--Map<String, Object> getUserToMap(@Param("id") int id);-->
<!--结果: {password=123456, sex=男 , id=1, age=23, username=admin}-->
<select id="getUserToMap" resultType="map"> select * from t_user where id = #{id}
</select>
2.5 查询多条数据为map集合
①方式一
/**
*查询所有用户信息为map集合
*@return
*将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此 时可以将这些map放在一个list集合中获取
*/
List<Map<String, Object>> getAllUserToMap();
<!--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();
<!--Map<String, Object> getAllUserToMap();-->
<!--
{
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=张三}
}
-->
<select id="getAllUserToMap" resultType="map"> select * from t_user
</select>
3. 特殊SQL的执行
3.1 模糊查询
/**
*测试模糊查询
*@param mohu
*@return
*/
List<User> testMohu(@Param("mohu") String mohu);
<!--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>
3.2 批量删除
/**
*批量删除
*@param ids
*@return
*/
int deleteMore(@Param("ids") String ids);
<!--int deleteMore(@Param("ids") String ids);-->
<delete id="deleteMore">
delete from t_user where id in (${ids})
<!-- 使用$符号,${ids}是字符串形式的id的集合,可以使用逗号隔开,也可以使用分号隔开-->
</delete>
3.3 动态设置 表名
/**
*动态设置表名,查询所有的用户信息
*@param tableName
*@return
*/
List<User> getAllUser(@Param("tableName") String tableName);
<!--List<User> getAllUser(@Param("tableName") String tableName);-->
<select id="getAllUser" resultType="User"> select * from #{tableName}
</select>
3.4 添加功能获取自增的主键
场景模拟:
t_clazz(clazz_id,clazz_name) t_student(student_id,student_name,clazz_id)
1、添加班级信息
2、获取新添加的班级的id
3、为班级分配学生,即将某学的班级id修改为新添加的班级的id
/**
*添加用户信息
*@param user
*@return
*useGeneratedKeys:设置使用自增的主键
*keyProperty:因为增删改有统一的返回值是受影响的行数,
*因此只能将获取的自增的主键放在传输的参数user对象的某个属性中
*/
int insertUser(User 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
4.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 like concat('%',#{mohu},'%')
</select>
若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性 名符合Java的规则(使用驼峰)
此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系
a > 可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
b > 可以在MyBatis的核心配置文件中设置一个全局配置信 mapUnderscoreToCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰
例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为
userName
4.2 多对一映射处理
场景模拟:
查询员工信息以及员工所对应的部门信息
4.2.1 级联方式处理映射关系
<resultMap id="empDeptMap" type="Emp">
<id column="eid" property="eid"></id>
<result column="ename" property="ename"></result>
<result column="age" property="age"></result>
<result column="sex" property="sex"></result>
<result column="did" property="dept.did"></result>
<result column="dname" property="dept.dname"></result>
</resultMap>
<!--Emp getEmpAndDeptByEid(@Param("eid") int eid);-->
<select id="getEmpAndDeptByEid" resultMap="empDeptMap">
select emp.*,dept.* from t_emp emp left join t_dept dept on emp.did = dept.did where emp.eid = #{eid}
</select>
4.2.2 使用association处理映射关系
<resultMap id="empDeptMap" type="Emp">
<id column="eid" property="eid"></id>
<result column="ename" property="ename"></result>
<result column="age" property="age"></result>
<result column="sex" property="sex"></result>
<association property="dept" javaType="Dept">
<id column="did" property="did"></id>
<result column="dname" property="dname"></result>
</association>
</resultMap>
<!--Emp getEmpAndDeptByEid(@Param("eid") int eid);-->
<select id="getEmpAndDeptByEid" resultMap="empDeptMap">
select emp.*,dept.* from t_emp emp left join t_dept dept on emp.did = dept.did where emp.eid = #{eid}
</select>
4.2.3 分步查询
实体类 (注: 此处使用了 Lombok的依赖, 省略写了get方法和set方法等)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private Integer id;
private String name;
private String gender ;
private Double salary ;
private Date joinDate ;
private Integer deptId;
private Dept dept;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Dept {
private Integer id;
private String name;
}
①查询员工信息
/**
*通过分步查询查询员工信息
*@param eid
*@return
*/
Emp getEmpByStep(@Param("eid") int eid);
<resultMap id="empDeptStepMap" type="Emp">
<id column="eid" property="eid"></id>
<result column="ename" property="ename"></result>
<result column="age" property="age"></result>
<result column="sex" property="sex"></result>
<!--
select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId)
column:将sql以及查询结果中的某个字段设置为分步查询的条件
-->
<association property="dept"
select="com.softeem.MyBatis.mapper.DeptMapper.getEmpDeptByStep"
column="did">
</association>
</resultMap>
<!--Emp getEmpByStep(@Param("eid") int eid);-->
<select id="getEmpByStep" resultMap="empDeptStepMap">
select * from t_emp where eid = #{eid}
</select>
注: property="dept"中的 dept是Emp实体类中的一个属性,如果Emp实体类中没有这个属性, 这里的dept会报红
②根据员工所对应的部门id查询部门信息
/**
*分步查询的第二步: 根据员工所对应的did查询部门信息
*@param did
*@return
*/
Dept getEmpDeptByStep(@Param("did") int did);
<!--Dept getEmpDeptByStep(@Param("did") int did);-->
<select id="getEmpDeptByStep" resultType="Dept"> select * from t_dept where did = #{did}
</select>
4.3 一对多映射处理
实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private Integer id;
private String name;
private String gender ;
private Double salary ;
private Date joinDate ;
private Integer deptId;
private Dept dept;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Dept {
private Integer id;
private String name;
private List<Emp> empList;
}
4.3.1 collection
/**
*根据部门id查新部门以及部门中的员工信息
*@param did
*@return
*/
Dept getDeptEmpByDid(@Param("did") int did);
<resultMap id="deptEmpMap" type="Dept">
<id property="did" column="did"></id>
<result property="dname" column="dname"></result>
<!--
ofType:设置collection标签所处理的集合属性中存储数据的类型
-->
<collection property="emps" ofType="Emp">
<id property="eid" column="eid"></id>
<result property="ename" column="ename"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
</collection>
</resultMap>
<!--Dept getDeptEmpByDid(@Param("did") int did);-->
<select id="getDeptEmpByDid" resultMap="deptEmpMap">
select dept.*,emp.* from t_dept dept left join t_emp emp on dept.did = emp.did where dept.did = #{did}
</select>
注: property="emps"中的 emps是Dept实体类中的一个属性,如果Dept实体类中没有这个属性, 这里的emps会报红出错
4.3.2 分步查询
①查询部门信息
/**
*分步查询部门和部门中的员工
*@param did
*@return
*/
Dept getDeptByStep(@Param("did") int did);
<resultMap id="deptEmpStep" type="Dept">
<id property="did" column="did"></id>
<result property="dname" column="dname"></result>
<collection property="emps" fetchType="eager" select="com.softeem.MyBatis.mapper.EmpMapper.getEmpListByDid" column="did">
</collection>
</resultMap>
<!--Dept getDeptByStep(@Param("did") int did);-->
<select id="getDeptByStep" resultMap="deptEmpStep"> select * from t_dept where did = #{did}
</select>
②根据部门id查询部门中的所有员工
/**
*根据部门id查询员工信息
*@param did
*@return
*/
List<Emp> getEmpListByDid(@Param("did") int did);
<!--List<Emp> getEmpListByDid(@Param("did") int did);-->
<select id="getEmpListByDid" resultType="Emp"> select * from t_emp where did = #{did}
</select>
分步查询的优点:可以实现延迟加载
但是必须在核心配置文件中设置全局配置信息:
lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载。此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和collection中的fetchType属性设置当前的分步查询是否使用延迟加载, fetchType="lazy(延迟加载)|eager(立即加载)"
5. 动态SQL
Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了 解决 拼接SQL语句字符串时的痛点问题。
5.1 if
if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行
<!--List<Emp> getEmpListByCondition(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>
5.2 where
where和if一般结合使用:
a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and去掉
注意:where标签不能去掉条件最后多余的and
<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>
5.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>
5.4 SQL片段
sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入
<sql id="empColumns">
eid,ename,age,sex,did
</sql>
select <include refid="empColumns"></include> from t_emp
5.5 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.6 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>