zoukankan      html  css  js  c++  java
  • mybatis入门(八)

    mybatis入门---更新和删除

    <!-- 删除用户 -->
        <delete id="deleteUser" parameterType="java.lang.Integer">
         delete from user where id=#{id}
        </delete>
        
        <!-- 更新用户
        必须指定id,否则将会将表的内容全部更新
         -->
        <update id="updateUser" parameterType="ql.mybatis.pojo.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
        </update>

    测试类:

        // 删除用户
        @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();
                }
    
            }
        }
  • 相关阅读:
    【Android】HAL分析
    【qt】QT 的信号与槽机制
    【驱动】DM9000A网卡驱动框架源码分析
    【驱动】LCD驱动(FrameBuffer)分析
    告别我的OI生涯
    诸神的黄昏——北林退役帖合集
    cf592d
    北京林业大学就读体验
    hdu 5442 (ACM-ICPC2015长春网络赛F题)
    JAVA入门[4]-IntelliJ IDEA配置Tomcat
  • 原文地址:https://www.cnblogs.com/ql211lin/p/4528039.html
Copyright © 2011-2022 走看看