对上文-》Mybatis快速入门-《进行代码修改
1.在UserMapper.xml中添加插入操作
<!-- 插入操作-->
<insert id="save" parameterType="com.hao.domain.User">
insert into user values(#{id},#{username},#{password})
</insert>
parameterType意思是从Service业务层传过来的数据封装到了User对象中,该代码中的#{id}等代表占位符,与实体类User中的属性一一对应;
2.测试
public class MybatisTest {
@Test
public void test() throws IOException {
User user=new User();
user.setUsername("zsh");
user.setPassword("hao");
// 加载核心配置文件
InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 获得工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(stream);
// 获得session对象
SqlSession sqlSession = build.openSession();
// 参数:namespace+id
sqlSession.insert("userMapper.save",user);
sqlSession.commit();
}
}
mybatis默认事务是不提交的,所以需要手动commit;

至于这里出现id为7而不是6是因为我第一次没有提交事务,,但是数据已经传入过去
,所有id=6已经被默认使用,第二次再测试时执行commit()提交事务,所以id=7

浙公网安备 33010602011771号