删除用户和更新用户
配置文件
<!-- 删除用户
根据id删除用户,需要输入id值 -->
<delete id="deleteUser" parameterType="java.lang.Integer">
DELETE FROM user WHERE id=#{id}
</delete>
<!-- 更新用户
需要传入用户的id
需要传入用户的更新信息
parameterType指定user对象,包括id和更新信息,注意:id必须存在
#{id}:从输入user对象中获取id属性值
-->
<update id="updateUser" parameterType="cn.iven.mybatis.po.User">
UPDATE user SET username=#{name},birthday=#{birthday},sex=#{sex},address=#{address}
WHERE id=#{id}
</update>
程序代码
@Test
//删除用户信息
public void deleteUser() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.delete("test.deleteUser", 27);
//提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
//更新用户信息
public void updateUser() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(28);
user.setBirthday(new Date());
user.setName("Chloe");
user.setAddress("jxgz");
user.setSex("2");
sqlSession.update("test.updateUser", user);
//提交事务
sqlSession.commit();
sqlSession.close();
}