一.续
接上一次说到的,运行代码出现错误
这个错误是由于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>
不太理解这样用的意义在哪里~