Mybatis更新单条记录

Mybatis更新单条记录

parameterType:需要更新的用户信息
#{id}:从输入的user对象中获取ID属性,名称需要和属性名一致

映射文件


        update user set username = #{username},birthday = #{birthday},sex = #{sex},address = #{address} where id = #{id}

测试用例:

@Test
    public void testUpdateUser() throws Exception{
        //创建会话工厂
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource );
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过工厂得到SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //把高月改名为姬如千泷
        User user = new User();
        user.setId(2);
        user.setUsername("姬如千泷");
        user.setAddress("秦时明月之君临天下");
        user.setSex('0');
        user.setBirthday(new Date());
        //使用SqlSession操作数据库
        int result = sqlSession.update("test.updateUserByID", user);
        System.out.println(result);
        //手动提交事务
        sqlSession.commit();
        //关闭资源
        sqlSession.close();
    }

可能发生There is no getter for property named ‘value’ in ‘class com.hl.myabtis.first.beas.User’异常,参考:http://blog.csdn.net/leisure_life/article/details/72636547

你可能感兴趣的:(mybatis)