单表操作CRUD
插入
普通插入
- parameterType可选参数可不写,会自动匹配
-
<insert id="insertOne" parameterType="com.mbyte.easy.admin.entity.Student"> insert into student (name, img, sex, create_time) values ( #{student.name,jdbcType=VARCHAR}, #{student.img,jdbcType=VARCHAR}, #{student.sex,jdbcType=INTEGER}, #{student.createTime,jdbcType=TIMESTAMP} ) </insert>
回填主键
useGeneratedKeys="true" keyProperty="id"
<!--回填主键:useGeneratedKeys="true" keyProperty="id" --> <insert id="insertTwo" parameterType="com.mbyte.easy.admin.entity.Student" useGeneratedKeys="true" keyProperty="id"> insert into student (name, img, sex, create_time) values ( #{student.name,jdbcType=VARCHAR}, #{student.img,jdbcType=VARCHAR}, #{student.sex,jdbcType=INTEGER}, #{student.createTime,jdbcType=TIMESTAMP} ) </insert>
// 回填主键,执行完毕之后,student2中id自动赋值 studentMapper.insertTwo(student2); // 直接可以获取到数据库生成的主键id student2.getId(); System.out.println("student2:"+student2);
批量插入
<insert id="insertBatch">
insert into student (name, img, sex, create_time)
values
<foreach collection="studentList" item="student" separator=",">
(
#{student.name,jdbcType=VARCHAR},
#{student.img,jdbcType=VARCHAR},
#{student.sex,jdbcType=INTEGER},
#{student.createTime,jdbcType=TIMESTAMP}
)
</foreach>
</insert>
删除
单个删除
<delete id="deleteSutdentById" parameterType="java.lang.Long" >
delete from student where id = #{id,jdbcType=BIGINT}
</delete>
<delete id="deleteByIds" parameterType="java.lang.Long" >
delete from student where id in
<foreach collection="idList" index="index" item="item"
open="(" separator="," close=")">
#{item}
</foreach>
</delete>
更新
<!--注意字段判断-->
<update id="updateStuddent" >
update student
<set>
<if test="student.name != null">
name = #{student.name,jdbcType=VARCHAR},
</if>
<if test="student.img != null">
img = #{student.img,jdbcType=VARCHAR},
</if>
<if test="student.sex != null">
sex = #{student.sex,jdbcType=INTEGER},
</if>
<if test="student.createTime != null">
create_time = #{student.createTime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{student.id,jdbcType=BIGINT}
</update>