解决MyBatis获取刚插入数据的ID值
Mybatis获取刚插入数据的ID值有很多解决方法,目前采用以下方式进行获取。
添加完数据后直接返回刚添加数据的id
// UserDao.java
public static void addUser() throws Exception{InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserDao userDao = sqlSession.getMapper(UserDao.class);User user = new User();user.setUsername("system");user.setPassword("system");userDao.addUser(user);System.out.println(user);sqlSession.commit();sqlSession.close();
}// UserDao.xml
<insert id="addUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
<!--useGeneratedKeys:是够获取自动增长的主键值。true表示获取keyProperty :指定将获取到的主键值封装到哪儿个属性里
-->insert into tb_user(username,password) values(#{username},#{password})
</insert>