Java框架_Mybatis框架6_使用动态标签查询

    在进行多条件查询时,还可以使用动态标签来拼接sql,此外,利用动态标签,还可以满足对数据库表的批量删除。列举下面两个使用场景:

※场景一:利用多条件查询,查询同时满足价格为2000,且品牌为“小米”的所有结果:

SQL语句应该为:select * from items where items_name = #{itemsName} and price = #{price}

使用动态标签:

	<select id="findItemsByNameAndPrice" parameterType="items" resultMap="itemsMap">
		select * from items
		<!-- where标签代表多条件查询,会过滤掉多余的and字符 -->
		<where>
			<if test="itemsName!=null and itemsName!=''">
				and items_name = #{itemsName}
			</if>
			<if test="price!=null and price!=''">
				and price = #{price}
			</if>			
		</where>
	</select>

where标签会自动去掉满足条件的第一个and,if中的test属性用于空值检测

※场景二:根据id值,来对数据库表进行批量删除:

SQL语句:delete from items where items_id in (1,3,4);

动态标签:

	<delete id="deleteItems" parameterType="com.mybatis.vo.ItemsVo">
		delete from items
		<where>
			<foreach collection="ids" open="items_id in(" close=")" item="id" separator=",">
				#{id}
			</foreach>
		</where>
	</delete>

foreach标签可以允许你指定一个集合来进行遍历

    collection:表示传入的为一个集合

    open :表示以什么开始,比如上面中的以"items_id in (" 开始

    close :表示以什么结束

    items:集合中元素迭代时的别名

    separator : 每次进行迭代的分隔符

PS:传进来的参数为一个VO封装的List:

public class ItemsVo {
	private List<Integer> ids;

	public List<Integer> getIds() {
		return ids;
	}

	public void setIds(List<Integer> ids) {
		this.ids = ids;
	}
	
}

猜你喜欢

转载自blog.csdn.net/m0_37808093/article/details/81128618
今日推荐