输入输出映射
- 输入映射支持的类型
八大数据类型 list map POJO 包装类型
包装类可以直接通过对象导航的方式不断向下获取 - 八大数据类型 list map POJO 包装类型
输出包装类型时需要自动映射字段
动态SQL语句
- 什么是动态的SQL语句
- 动态sql是可以在sql语句上添加条件 判断 循环等动态标签 ..
- 有哪些常用的动态标签
- 标签 进行条件的判断
- 拼接多个参数 自动删除第一个and
- 用来遍历集合
- 定义sql语句的片段 抽取重复代码
- 用法,下面使用实例
- 当需求多次操作数据便会产很多的重复语句这时我们可以把重复的sql语句片段抽取出来使用
抽取sql
- 当需求多次操作数据便会产很多的重复语句这时我们可以把重复的sql语句片段抽取出来使用
<!-- 如果很多sql重复的 没必要每次都写 可以对他进行抽取 -->
<sql id="selectUser">
select *from User
</sql>
拼接sql
<select id="getUser" parameterType="User" resultType="User">
<include refid="selectAll"/> where sex=#{sex} and name=#{name}
</select>
2. 和的使用
<!--where 标签的作用 执行内部的逻辑并拼接到外部的sql中 自动删除第一个 and -->
<where>
<!--if标签 -->
<if test="name !=null and name!= ''">
and name= #{name}
</if>
<if test="sex !=null and sex != ''">
and sex= #{sex}
</if>
</where>
整合后的sql语句
<select id="getUser" parameterType="User" resultType="User">
<include refid="selectAll"/>
<where>
<if test="sex !=null and sex != ''">
and sex=#{sex}
</if>
<if test="name !=null and name != ''">
and name=#{name}
</if>
</where>
</select>
3.
<!-- 根据一堆id查询
forEach标签遍历参数
collection 指定被遍历的集合
item 每一次遍历得到的对象
separator 分隔符
open 开始的标记
close 结束的标记
-->
<select id="selectUserByIds" parameterType="java.util.List" resultType="User">
<include refid="selectUser"/> where
id in
<foreach collection="list" item="item" separator="," open="(" close=")">
#{item}
</foreach>
</select>
Mybatis连接查询
1.一对多查询
<!--一对多 手动映射 -->
<resultMap type="User" id="UserMap">
<result property="name" column="u_name"/>
<result property="id" column="u_id"/>
<collection property="orders" autoMapping="true" ofType="Orders">
<result property="name" column="o_name"/>
<result property="id" column="o_id"/>
</collection>
</resultMap>
<!-- 一对多查询 -->
<select id="getAllUser" resultType="User" resultMap="UserMap">
SELECT * ,orders.name as o_name,orders.id as o_id ,User.id as u_id,User.name as u_name
FROM User LEFT join orders on user.id = orders.userid
</select>
多对一
<resultMap type="Groups" id="GroupsMap" autoMapping="true">
<id property="g_id" column="g_id"/>
<!-- 坑点:多对多查询时 如果完全使用自动映射
相同记录如果有不同的关联记录会生成多个对象
我们希望是 将关联的数据放到集合中不是创建新的对象
手动映射任意一条记录 就行
-->
<result property="g_id" column="g_id"/>
<collection property="users" ofType="User" autoMapping="true"></collection>
</resultMap>
<select id="GetAllGroups" resultMap="GroupsMap">
select * from groups left join mideel on groups.g_id = mideel.g_id
left join User on mideel.u_id = User.id
</select>