Mybatis技术第三次练习-动态SQL

文章讲述了遇到Java运行时版本与编译版本不兼容的问题,解决后发现是数据库缺乏数据导致无结果。然后重点讨论了MyBatis中的动态SQL,包括if、where、choose、foreach和bind标签的使用,展示了如何实现条件查询和列表参数处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.续

接上一次说到的,运行代码出现错误

 

这个错误是由于Java运行时版本与编译Java代码所使用的版本不兼容导致的。然后我修改了eclipse的编译java代码的版本.

接着继续运行代码,发现没有任何反应.

我一度以为那里又错了,找不到原因.经过思考,既然运行没有报错,说明代码是没有问题的.然后我开始一点一点的检查,我突然想起来,没有输出结果,也许是数据库根本没有数据.然后我跑去看数据库,果然,数据库里缺少数据.只能说自己太傻了,还找了半天问题~~~

二.动态SQL

        1.if标签:

<select id="listProduct" resultType="Product">
	select * from product_
	<if test="name!=null">
		where name like concat('%',#{name},'%')
	</if>		 	
</select>

        if标签用于实现条件查询,如果name变量不为空,则在查询中添加一个模糊匹配语句,查询名字包含指定关键字的产品。

        2.where标签:

<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>

where标签用于限制查询条件,其中包含了两个if标签,分别用于实现根据名称和价格进行查询。如果name变量不为空,则在查询中添加一个模糊匹配语句,查询名字包含指定关键字的产品;如果price变量不为空且不为0,则在查询中添加一个条件语句,查询价格高于指定值的产品。

set标签与where标签用法是一致的

trim标签可以用来定制使用什么标签

        3.choose标签

Mybatis里面没有else标签,但是可以使用when otherwise标签来达到这样的效果。

<select id="listProduct" resultType="Product">
	  SELECT * FROM product_ 
	  <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>
</select>

where标签用于限制查询条件,其中包含了choose标签和otherwise标签。如果name变量不为空,则在查询中添加一个模糊匹配语句,查询名字包含指定关键字的产品;如果price变量不为空且不为0,则在查询中添加一个条件语句,查询价格高于指定值的产品;否则,将id大于1的产品都作为查询结果返回。

        4.foreach标签

 SELECT * FROM product_ 
 	WHERE ID in
			<foreach item="item" index="index" collection="list"
    			open="(" separator="," close=")">
      		             #{item}
			</foreach>

        通过foreach标签和in操作符,在ID列上使用列表参数实现对特定产品集合的筛选。

        

        5.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="com.how2java.pojo">
        <!-- 本来的模糊查询方式 -->
<!--         <select id="listProduct" resultType="Product"> -->
<!--             select * from   product_  where name like concat('%',#{0},'%') -->
<!--         </select> -->
             
        <select id="listProduct" resultType="Product">
            <bind name="likename" value="'%' + name + '%'" />
            select * from   product_  where name like #{likename}
        </select>
         
    </mapper>

不太理解这样用的意义在哪里~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值