MyBatis返回插入的主键ID

Mybatis支持mysql数据库中insert操作返回的主键操作,

1.如果insert操作的类型(ParameterType)为map,对应的方法为:

(1)mapper.xml文件:

  

<!-- 插入一条数据 -->  
    <insert id="insert"  parameterType="java.util.Map" useGeneratedKeys="true" keyProperty="id" keyColumn="id">  
        <selectKey resultType="int" order="AFTER" keyProperty="id">   
            SELECT LAST_INSERT_ID() as id  
        </selectKey>  
            
        insert into sys_organization_info (name,level,parent_id,create_time,name_path)   
        values (#{name,jdbcType=VARCHAR},  
        #{level,jdbcType=TINYINT},  
        #{parent_id,jdbcType=NUMERIC},  
        #{create_time,jdbcType=DATE},  
        #{name_path,jdbcType=VARCHAR})  
    </insert>  

(2)对应上面的insert操作,会将insert完后的“自增的主键”(keyProperty对应的字段值),以key为keyProperty对应的属性值,放在map中,在dao或者service层,通过

sysOrganizationDao.insert(map);  
int i = Integer.parseInt(map.get("id").toString());

  即可获取。

2.如果insert操作的对象是实体bean类,则

(1)mapper.xml中配置文件为:

    <insert id="insert" parameterType="com.xxx.xxxx.pojo.User">
        insert into t_user (name) 
        values (#{user.name})
        <selectKey resultType="Integer" order="AFTER" keyProperty="user.userId">
            SELECT LAST_INSERT_ID() AS userId
        </selectKey>
    </insert>
 

或者和useGenerateKeys标签组合使用:

useGeneratedKeys 取值范围true|false 默认值是:false。 含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。
<insert id="insert" parameterType="com.xxx.xxxx.pojo.User" useGeneratedKeys="true" keyProperty="id">    
        insert into system(name) values(#{name})    
</insert>
注意:使用该方法时,直接通过bean对象的get()属性方法即可。

(2)在service层获取该记录的id操作时,

@Override
public void insert() {
    User user = new User();
    user.setName("test");              
    dao.insert(user); 
    System.out.println(user.getUserId); //发现ID已经获取了
}

  即可获取对应的记录id.

 

 

 

 

posted @ 2018-04-23 21:20  alionse  阅读(378)  评论(0)    收藏  举报