mybatis动态sql之新增与更新方式
作者:某猿蚊常叮
这篇文章主要介绍了mybatis动态sql之新增与更新方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
mybatis动态sql新增与更新
记录一个简单的mybatis动态sql例子
新增
<?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="org.ruiskey.mapper.UserMapper">
<insert id="save">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null and id != ''">
id,
</if>
<if test="username != null and username != ''">
username,
</if>
<if test="password != null and password != ''">
password,
</if>
<if test="nickname != null and nickname != ''">
nickname,
</if>
<if test="email != null and email != ''">
email,
</if>
<if test="phone != null and phone != ''">
phone,
</if>
<if test="address != null and address != ''">
address
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null and id != ''">
#{id},
</if>
<if test="username != null and username != ''">
#{username},
</if>
<if test="password != null and password != ''">
#{password},
</if>
<if test="nickname != null and nickname != ''">
#{nickname},
</if>
<if test="email != null and email != ''">
#{email},
</if>
<if test="phone != null and phone != ''">
#{phone},
</if>
<if test="address != null and address != ''">
#{address}
</if>
</trim>
</insert>
</mapper>更新
<update id="update">
update user
<set>
<if test="username != null and username != ''">
username = #{username}
</if>
<if test="password != null and password != ''">
password = #{password}
</if>
<if test="nickname != null and nickname != ''">
nickname = #{nickname}
</if>
<if test="email != null and email != ''">
email = #{email}
</if>
<if test="phone != null and phone != ''">
phone = #{phone}
</if>
<if test="address != null and address != ''">
address = #{address}
</if>
</set>
<where>
id = #{id}
</where>
</update>mybatis动态SQL增删改查
我们在对数据库进行增删改查的时候,很多时候我们并不确定我们要进行传入的参数的个数,种类以及是否为空。
此时我们就需要用到mybatis动态sql来对数据库进行灵活的交互。
- 步骤一:导入相关jar包,编写连接数据库的MybatisUtil工具类
- 步骤二:在src下配置mybatis.xml配置文件。其中对数据库连接,映射文件的加载进行配置。(简写配置可选)
- 步骤三:建立实体类Student

- 步骤四:增删改查的方法以及映射文件StudentMapper.xml中配置的编写。
添加数据

insert 对应的映射文件中配置:



通过传入数组参数删除

deleteArray对应的映射文件中配置:

通过传入List集合参数进行删除

deleteList 对应的映射文件中配置:


更新数据

update 对应的映射文件中配置:

神奇的是:

查找数据

findAll对应的映射文件配置

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
