MyBatis+MySQL 返回插入的主键ID
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User"> insert into user(userName,password,comment) values(#{userName},#{password},#{comment}) </insert>
public class User { private int userId; private String userName; private String password; private String comment; //setter and getter }
public interface UserDao { public int insertAndGetId(User user); }
User user = new User(); user.setUserName("chenzhou"); user.setPassword("xxxx"); user.setComment("测试插入数据返回主键功能"); System.out.println("插入前主键为:"+user.getUserId()); userDao.insertAndGetId(user);//插入操作 System.out.println("插入后主键为:"+user.getUserId());