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

上一篇:Java学习之Mybatis框架基础篇


下一篇:Spring中Bean之间的依赖的实现方式dv发的个