目录
1.模糊查询
<select id="getNameLike" resultMap="BaseResultMap">
select * from dish like concat('%',#{name},'%')
</select>
select * from dish where name like '%${name}}%'
2.自增主键
传输一个实体过来,运行sql新增数据之后,这个实体的id属性被赋值。
3.条件查询
这种需求需要使用到 <choose(when, otherwise )>标签 实现, 而 choose 标签类似于 Java 中的 switch 语句.
*choose--->switch
*when------>Case
*otherwise--->default
+++ when包裹着部分sql,when后面的test需要写逻辑表达式确认是否参与sql语句
+++<choose>包裹着所有的<when>
+++<otherwise>包裹着其他选择
相当于java的 if else 语句
<!-- 条件查询-->
<select id="getByStatusAfter" resultMap="BaseResultMap">
select * from dish
<where>
<choose>
<when test="status =='1' "> and status = 1 </when>
<otherwise>
and status = 0
</otherwise>
</choose>
<choose>
<when test="name =='wrx' "> and name = 1 </when>
<otherwise>
and status = 0
</otherwise>
</choose>
</where>
</select>
4.多表级联查询 association 标签
通过category表的id,获取category表的name属性,并且获取,setmeal表的name和price属性。在mybatis里如何定义resultMap?
1.在category的实体类添加Setmeal实体属性
2.在xml里定义ResultMap,使用 association 标签
<resultMap id="categoryMap2" type="com.wrx.domain.Category">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="type" column="type" jdbcType="INTEGER"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="sort" column="sort" jdbcType="INTEGER"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
<result property="createUser" column="create_user" jdbcType="BIGINT"/>
<result property="updateUser" column="update_user" jdbcType="BIGINT"/>
<-- propert属性名 javaType 实体类类型 -->
<association property="setmeal" javaType="com.wrx.domain.Setmeal">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="categoryId" column="category_id"/>
<result property="name" column="name"/>
<result property="price" column="price"/>
</association>
</resultMap>
<select id="getDishAdndSetmeal" resultMap="categoryMap2">
select
t1.name ,t2.name ,t2.price
from category t1
left join setmeal t2 on t1.id = t2.category_id
where t1.id = #{id}
</select>
5.分步查询和延迟加载
在mybatis配置文件开启延迟加载
在xml里面写好分布查询的sql和resultMap
1.标红色的是查询第二个表的sql对应的mapper文件里的方法名的全路径名。
2.查询结果同目录4。区别在于,把一个sql分成两个基础sql。
3.然后开启延迟加载,就可以获取在需要dept这个属性时候在进行sql查询。
4.如果需要需要直接加载,给association添加属性fetchType ,赋值eager就是直接加载lazy就是延迟加载。