mybatis入门---更新和删除
delete from user where id=#{id} update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
测试类:
// 删除用户 @Test public void deleteUserTest() throws IOException { // 通过工厂得到SqlSession SqlSession sqlSession = null; try { // mybatis配置文件 String resource = "SqlMapConfig.xml"; // 得到配置文件流 InputStream inputStream = Resources.getResourceAsStream(resource); // 创建会话工厂,传入mybatis的配置文件信息 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); sqlSession = sqlSessionFactory.openSession(); sqlSession.delete("test.deleteUser", 1); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { // 释放资源 sqlSession.close(); } } } //更新用户 @Test public void updateUserTest() throws IOException { // 通过工厂得到SqlSession SqlSession sqlSession = null; try { // mybatis配置文件 String resource = "SqlMapConfig.xml"; // 得到配置文件流 InputStream inputStream = Resources.getResourceAsStream(resource); // 创建会话工厂,传入mybatis的配置文件信息 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); sqlSession = sqlSessionFactory.openSession(); User user=new User(); user.setId(22); user.setUsername("陈大明"); user.setBirthday(new Date()); user.setAddress("福建福州"); user.setSex("2"); sqlSession.update("test.updateUser",user); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { // 释放资源 sqlSession.close(); } } }