MyBatis 笔记

参数

参数可以使用 #{username} 或者 ${username} 来表示(示例为用户名的值),一般来说,直接使用 # 更方便,它会自动进行类型转换,而 $ 是直接将值插入,不进行任何转换。

举个例子,语句 update t_user set username = #{username} 最终的语句是 update t_user set username = 'John',而使用 $ 则为 update t_user set username = John,显然语法不正确。

常用 tag

resultMap
  association(property, resultMap, columnPrefix)
  collection(property, ofType, resultMap, columnPrefix)

插入后设置自增主键ID

PostgreSQL 不支持使用useGeneratedKeys="true" keyProperty="id"自动设置主键ID:


  insert into Author (username, password) values

所以需要使用 selectKey 的方式(keyProperty 指定写入到
parameterType 对应的属性名,resultType 是对应属性的类型):


  
            SELECT currval('t_area_id_seq')
  
  insert into Author
    (username, password)
  values
    (#{username}, #{password})

这样你传入进来的对象的 id 属性就会在成功插入后赋值。

// 未设置 id
Author author = new Author();
author.setUsername("name");
author.setPassword("psw");

int insertedCount = mapper.insertAuthor(author); // 成功插入的数量
int id = author.getId(); // 被赋值的 id

你可能感兴趣的:(MyBatis 笔记)