首页 > 代码库 > Mybatis中插入记录后获取该条记录ID

Mybatis中插入记录后获取该条记录ID

一、POJO

public class User {
	
	private Integer userId;
	private String name;
	public Integer getUserId() {
		return userId;
	}
	public void setUserId(Integer userId) {
		this.userId = userId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

二、数据库表

CREATE TABLE `t_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘用户ID‘,
  `name` varchar(18) NOT NULL COMMENT ‘用户名‘,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘用户表‘

三、Mybatis映射文件中SQL语句

    <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>

 

四、Dao层接口

void insert(@Param("user") User user);

五、Service层实现

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

  

 

Mybatis中插入记录后获取该条记录ID