U01_04 MyBatis添加操作

1. 添加create

概念:

  • 添加业务使用 <insert>
  • parameterType:参数使用Student实体的类型类全名,可省略。
  • resultType:添加业务没有返回值,必须省略。
  • SQL语句中,#{xxx} 是占位符,一般用于等号后,如果传入的是POJO类型,那么 #{} 中的内容必须是POJO中对应的属性名,如果POJO还埋了其它的POJO对象,如 clazz ,那么 #{} 中可填 clazz.clazz_name 这样的格式内容。
  • 添加业务中,当你的主键为自增时:
    • 不指定id,则POJO中id属性值必须为null,否则会报错。
    • 指定了id,则POJO中id属性值可以自己指定,如果不指定,则仍为自增。

配置: mapper/StudentMapper.xml 中添加

<insert id="create">
    INSERT INTO `student` 
    (`stu_name`, `stu_age`, `stu_gender`, `stu_info`) 
    values 
    (#{stuName}, #{stuAge}, #{stuGender}, #{stuInfo})
</insert>
复制代码

源码: junit测试

@Test
public void create() {
    String resource = "mybatis/mybatis-student.xml";
    SqlSessionFactory factory = MybatisTool.getSqlSessionFactory(resource);

    Student guangkun = new Student();
    guangkun.setStuName("谢广坤");
    guangkun.setStuAge("58");
    guangkun.setStuGender("male");
    guangkun.setStuInfo("广坤山货");

    SqlSession session = factory.openSession();
    try {
        session.insert("studentSpace.create", guangkun);
        session.commit();
        System.out.println(guangkun);
    } catch (Exception e) {
        session.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}
复制代码

2. 自增主键回注方法一

概念: 如果你需要在添加一个数据之后自动将主键注回到入参的POJO中,且你的数据库支持主键自增:

  • useGeneratedKeys="true":表示使用自动主键生成机制,即主键回注。
  • keyProperty="id":指定主键数据回注到参数POJO的哪个字段中。
  • 这两个属性只有 <insert> 中才可以使用。

配置: mapper/StudentMapper.xml 中添加

<insert id="create" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO `student` 
    (`stu_name`, `stu_age`, `stu_gender`, `stu_info`) 
    values 
    (#{stuName}, #{stuAge}, #{stuGender}, #{stuInfo})
</insert>
复制代码

3. 自增主键回注方法二

概念: 主键回注还有一种方法,就是在 <insert> 中指定 <selectKey> 代码块。

  • <selectKey>:负责返回自增的主键。
  • order:相对于 <insert> 语句的执行时机
    • BEFORE:在 <insert> 之前。
    • AFTER:在 <insert> 之后。
  • keyProperty="id":指定主键数据回注到参数POJO的哪个字段中。
  • resultTypekeyProperty 中的值的类型全名,必须指定。
  • SQL语句中,last_insert_id() 函数可以得到上一次添加语句的自增ID。

配置: mapper/StudentMapper.xml 中添加

<selectKey order="AFTER" keyProperty="id" resultType="java.lang.Integer">
    SELETE LAST_INSERT_ID()
</selectKey>
复制代码

4. 非自增主键回注

概念: 如果MySql使用的不是主键自增,而是随机字符串,或者你使用的数据库不支持主键自增,那么添加时应该做如下改动:

配置: mapper/StudentMapper.xml 中添加

<selectKey order="BEFORE" keyProperty="id" resultType="java.lang.String">
    SELECT UUID()
</selectKey>
复制代码

别忘了将pojo中的id改为String类型。

猜你喜欢

转载自juejin.im/post/5ecb4254f265da77031b5786