MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
基本原理:
1. 应用程序找Mybatis要数据
2. mybatis从数据库中找来数据
(1) 通过mybatis-config.xml 定位哪个数据库
(2) 通过Category.xml执行对应的select语句
(3) 基于Category.xml把返回的数据库记录封装在Category对象中
(4)把多个Category对象装在一个Category集合中
3. 返回一个Category集合
添加数据:
删除数据:删除id=6的对象
查询数据:通过session.selectOne获取id=3的记录
修改数据:通过session.update进行修改
多对一查询:
动态sql
if标签:如果没有传参数name,那么就查询所有数据,如果有name参数,那么就对其进行模糊查询。
多条件判断 where标签:where 标签主要用来简化 SQL 语句中的条件判断,可以自动处理 AND/OR 条件。if 语句中判断条件为 true 时,where 关键字才会加入到组装的 SQL 里面,否则就不加入。where 会检索语句,它会将 where 后的第一个 SQL 条件语句的 AND 或者 OR 关键词去掉。set标签与where标签类似,处理在update语句中遇到多个字段相关的问题。
<select id="listProduct" resultType="Product">
select * from product_
<where>
<if test="name!=null">
and name like concat('%',#{name},'%')
</if>
<if test="price!=null and price!=0">
and price > #{price}
</if>
</where>
</select>
choose标签:在 mybaits 中,只有 if 标签,并没有 else 标签,可以使用 chose when otherwise 代替。
<where>
<choose>
<when test="name != null">
and name like concat('%',#{name},'%')
</when>
<when test="price !=null and price != 0">
and price > #{price}
</when>
<otherwise>
and id >1
</otherwise>
</choose>
</where>
foreach标签:foreach用来迭代传过来的参数。
collection:表示传入过来的参数的数据类型。
item: 循环体中的具体对象。
index:在 list 和数组中,index 是元素的序号;在 map 中,index 是元素的 key。
open:表示该语句以什么开始
close:表示该语句以什么结束
separator:表示在每次进行迭代之间以什么符号作为分隔符
SELECT * FROM product_
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
bind标签:可以避免因更换数据库而修改 SQL,通常用于模糊查询中。
<select id="listProduct" resultType="Product">
<bind name="likename" value="'%' + name + '%'" />
select * from product_ where name like #{likename}
</select>