文章目录
1.#与$有什么区别?
2.如何解决实体类属性名称与表字段名称不一致的情况?
- 在sql语句中使用别名
- 使用resultMap标签实现手动映射
3.如何实现多表关联查询的一对一、一对多及多对多的关系?
- 使用resultMap+association标签实现一对一
- 使用resultMap+collection标签实现一对多
- 使用resultMap+collection+collection标签实现多对多
4.如何实现模糊查询?
- 使用 like ‘%${value}%’
<select id="queryLikeByName" resultType="user"> select * from user where name like '%${value}%' </select>
- 使用bind标签
<select id="queryLikeByName" resultType="user"> <bind name="name" value="'%'+name+'%'"> select * from user where name like #{name} </select>
注意:使用bind标签时,里面的参数名称只能使用@Param("")的别名
5.DAO接口/MAPPER接口的原理是什么?接口中的方法可以重载吗?
Mybatis基于接口开发的实现原理是使用了JDK动态代理,在调用接口中方法时,Mybatis会为接口生成代理对象,代理对象会拦截接口中的方法,转而执行MappedStatement对象所代表的sql,然后将执行结果返回。其中MappedStatement对象产生于xml文件中的标签(每个select、insert等标签都会被解析成一个MappedStatement对象),Mybatis会将接口全限定名+方法名拼接为一个字符串作为一个key值,通过key值,可唯一定位到一个MappedStatement对象。
由于Mybatis使用的是接口全限定名+方法名作为key寻找指定的MappedStatement对象策略,所以接口中方法不能重载
6.如何实现动态SQL?
动态SQL是指根据表达式的值进行逻辑判断,然后动态拼接SQL。Mybatis提供了9中标签来实现
trim | where | set | if | choose | when | otherwise | foreach | bind
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.khue.mapper.UserMapper">
<!--
name有值执行:select * from user where name=#{name}
name无值执行:select * from user
-->
<select id="queryByConditon" resultType="user">
select * from user
<where>
<if test="name!=null and name!=''">and name=#{name}</if>
</where>
</select>
<select id="queryByConditon" resultType="user">
select * from user
<where>
<choose>
<when test="name!=null and name!=''">and name=#{name}</when>
<otherwise>1=1</otherwise>
</choose>
</where>
</select>
<select id="queryByConditon" resultType="user">
select * from user
<trim prefix="where" prefixOverrides="and">
<if test="name!=null and name!=''">and name=#{name}</if>
</trim>
</select>
<!--
name有值执行:update user set name=#{name} where id=#{id}
name无值执行:update user where id=#{id}
-->
<update id="updateByCondition">
update user
<set>
<if test="name!=null and name!=''">name=#{name},</if>
</set>
where id=#{id}
</update>
<update id="updateByCondition">
update user
<trim prefix="set" suffixOverrides=",">
<if test="name!=null and name!=''">name=#{name},</if>
</trim>
where id=#{id}
</update>
<!--
select * from user where id in(1,2,...)
参数为数组或可变参数时,collection为array
参数为List时,collection为list
-->
<select id="queryByCondition" resultType="user">
select * from user where id in
<foreach collection="array" open="(" separator="," close=")" item="id">#{id}</foreach>
</select>
<!--模糊查询-->
<select id="queryLikeByName" resultType="user">
<bind name="name" value="'%'+name+'%'">
select * from user where name like #{name}
</select>
</mapper>