mybatis实现插入数据是自动获取插入数据的ID值并封装到Bean对象中
作者:互联网
XML方式的配置实现插入数据是自动获取插入数据的ID值并封装到Bean对象中
<insert id="add" parameterType="com.itheima.domain.User"> <selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="int"> select last_insert_id() </selectKey> insert into user(username,birthday,sex,address)values (#{username},null,'男','xian') </insert>
test测试
Bean对象的id属性就不需要手动去set了 配置了上面的代码就会自动从数据库获取并封装到Bean的id属性中
public static void main(String[] args) throws Exception { InputStream in = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory s = builder.build(in); SqlSession sqlSession = s.openSession(); //通过SqlSession创建Dao接口的代理对象 IUserDao userdao = sqlSession.getMapper(IUserDao.class); User uu = new User(); uu.setUsername("hhaaaah2"); System.out.println(uu+"保存前"); userdao.add(uu); sqlSession.commit(); System.out.println(uu+"保存后");
标签:封装,uu,sqlSession,插入,Bean,mybatis,id 来源: https://www.cnblogs.com/gaoSJ/p/13073623.html