有两种方法(至少我知道)来获取一个插入记录的 ID:
例如,我们有一个类EntityDao:
public class EntityDao {
     private Long id;
     private String name;
     // other fields, getters and setters
}
1. 使用insert标签并返回一个对象实例
MyBatis 界面
public interface EntityDaoMapper {
    EntityDao insert(EntityDao entity);
}
MyBatis XML 映射器:
<insert id="insert" parameterType="com.package.EntityDao" useGeneratedKeys="true" keyColumn="entity_id" keyProperty="id">
    INSERT INTO some_table (name, type, other_fields, etc)
    VALUES (#{name}, #{type}, #{other_fields}, #{etc}) 
</insert>
示例代码:
    EntityDao saved = entityDaoMapper.insert(entityToSave);
    System.out.println(saved.getId());
2.使用selectandresultType标签只返回记录的ID
MyBatis 界面
public interface EntityDaoMapper {
    Long insert(EntityDao entity);
}
MyBatis XML 映射器:
<select id="insert" parameterType="com.package.EntityDao" resultType="long">
    INSERT INTO some_table (name, type, other_fields, etc)
    VALUES (#{name}, #{type}, #{other_fields}, #{etc}) 
    RETURNING entity_id       <-- id only or many fields
</select>
示例代码:
Long id = entityDaoMapper.insert(entityToSave);
System.out.println(id);