《Web应用技术》第十章 MyBatis

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值