2022年8月14日,如何运用MyBatis实现数据的增删改操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计486个文字,预计阅读时间需要2分钟。
执行以下SQL语句可以插入一条记录到`Author`表中,并获取插入的ID:
sqlINSERT INTO Author (id, username, password, email, bio) VALUES ('insertAuthor', 'username', 'password', 'email@example.com', 'bio') -- 插入ID='insertAuthor'
insert, update 和 delete
<!-- 添加 --><insert id="insertAuthor">
insert into Author (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email},#{bio})
</insert>
<!-- 修改 -->
<update id="updateAuthor">
update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>
<!-- 删除 -->
<delete id="deleteAuthor">
delete from Author where id = #{id}
</delete>
描述:对于插入(insert)语句,设置如下的语句之后,可在添加完语句之后,返回添加的逐渐ID
useGeneratedKeys="true"
keyProperty="id"
语句块的使用
说明:这里使用为,拼接SQL,将使用较多的语句,使用sql标签分离出来,在需要使用的地方,引用sql标签块即可,具体演示,如下的示例。
sql块的定义:
<sql id="uxmlserColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>引用的地方:
<select id="selectUsers" resultType="map">select
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="userColumns"><property name="alias" value="t2"/></include>
from some_table t1
cross join some_table t2
</select>
<include refid="userColumns">为引用,定义的sql块。
<property name="alias" value="t1"/>为设置其中的别名的定义。
温馨提示:对于sql标签块的使用,使用的是比较多的,并且比较方便,在编写sql语句的使用,我们经常需要考虑sql优化等问题,将查询的数据项,都一一的仔细罗列出来,这个也是对于sql优化,比较有用的一种,因此建议,可以考虑使用sql标签来替代星号的使用。
还有就是,可嵌套使用,但是注意,其中的包含顺序。以及property标签的设置。
本文共计486个文字,预计阅读时间需要2分钟。
执行以下SQL语句可以插入一条记录到`Author`表中,并获取插入的ID:
sqlINSERT INTO Author (id, username, password, email, bio) VALUES ('insertAuthor', 'username', 'password', 'email@example.com', 'bio') -- 插入ID='insertAuthor'
insert, update 和 delete
<!-- 添加 --><insert id="insertAuthor">
insert into Author (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email},#{bio})
</insert>
<!-- 修改 -->
<update id="updateAuthor">
update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>
<!-- 删除 -->
<delete id="deleteAuthor">
delete from Author where id = #{id}
</delete>
描述:对于插入(insert)语句,设置如下的语句之后,可在添加完语句之后,返回添加的逐渐ID
useGeneratedKeys="true"
keyProperty="id"
语句块的使用
说明:这里使用为,拼接SQL,将使用较多的语句,使用sql标签分离出来,在需要使用的地方,引用sql标签块即可,具体演示,如下的示例。
sql块的定义:
<sql id="uxmlserColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>引用的地方:
<select id="selectUsers" resultType="map">select
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="userColumns"><property name="alias" value="t2"/></include>
from some_table t1
cross join some_table t2
</select>
<include refid="userColumns">为引用,定义的sql块。
<property name="alias" value="t1"/>为设置其中的别名的定义。
温馨提示:对于sql标签块的使用,使用的是比较多的,并且比较方便,在编写sql语句的使用,我们经常需要考虑sql优化等问题,将查询的数据项,都一一的仔细罗列出来,这个也是对于sql优化,比较有用的一种,因此建议,可以考虑使用sql标签来替代星号的使用。
还有就是,可嵌套使用,但是注意,其中的包含顺序。以及property标签的设置。

