zoukankan      html  css  js  c++  java
  • mybatis crud基础

    修改

    1、接口

    2、配置文件

    一、基础crud

    1、select

    接口类

    User getUserById(int id);

    xml文件

        <!--id 方法名 resultType返回值类型 parameterType参数类型-->
        <select id="getUserById" resultType="com.wt.pojo.User" parameterType="int">
            select * from mybatis.user where id = #{id}
        </select>

    测试

      @Test
      public void getUsrByID(){
            SqlSession sqlSession = MyBatisUtil.getSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            User user = userDao.getUserById(1);
            System.out.println(user);
            sqlSession.close();
      }

    2、insert

    接口类

    int insertUser(User user);

    xml文件

      <insert id="insertUser" parameterType="com.wt.pojo.User">
            insert into mybatis.user(name, pwd) values(#{name}, #{pwd})
        </insert>

    测试

      @Test
      public void InsertUser(){
       SqlSession sqlSession = MyBatisUtil.getSession();
       UserDao userDao = sqlSession.getMapper(UserDao.class);
       userDao.insertUser(new User("fun", "123"));
       sqlSession.commit();
       sqlSession.close();
      }

    3、update

    接口类

    int updateUser(User user);

    xml文件

      <update id="updateUser" parameterType="com.wt.pojo.User">
            update mybatis.user set name = #{name},  pwd = #{pwd}  where id = #{id} ;
        </update>

    测试

      @Test
      public void updateUser(){
            SqlSession sqlSession = MyBatisUtil.getSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            userDao.updateUser(new User(1, "aishe", "123"));
            sqlSession.commit();
            sqlSession.close();
      }

    4、delete

    接口类(Mapper)

    int deleteUser(int id);

    xml

        <delete id="deleteUser" parameterType="int">
            delete from mybatis.user where id = #{id}
        </delete>

    测试

      @Test
      public void deleteUser(){
           SqlSession sqlSession = MyBatisUtil.getSession();
           UserDao userDao = sqlSession.getMapper(UserDao.class);
           userDao.deleteUser(2);
           sqlSession.commit();
           sqlSession.close();
      }

    注意:

    1、insert update delete commit

    2、insert update delete  方法类型 int

  • 相关阅读:
    Hibernate 笔记 之 三 基础优化方面
    Hibernate 笔记 之 二 查询
    Hibernate 笔记 之 一 创建与配置
    hibernate初次配置及测试
    CentOS 7.3 安装MySQL--Java--Tomcat
    Spring AOP:自动注入参数值
    Spring AOP:实现Request信息获取
    IntelliJ IDEA导出项目文档
    IntelliJ IDEA:Shortcut Key
    iText生成PDF
  • 原文地址:https://www.cnblogs.com/wt7018/p/13329593.html
Copyright © 2011-2022 走看看