Mybatis(crud)


namespace

namespace中包名要和Dao/mapper接口的包名一致

xml标签配置

选择,查询语句:
id:就是对应的namespace中的方法名:
resultType:Sql语句执行的返回值!
parameterType:参数类型!

select

编写接口

List getUserList();

编写mapper中的sql语句


测试

@Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userDao=sqlSession.getMapper(UserMapper.class);
        List userlist =userDao.getUserList();
        for (User user : userlist) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }

insert

编写接口

    //insert 一个用户
    int addUser(User user);

编写mapper中的sql语句


        insert  into mybatis.user(id,name,pwd)values (#{id},#{name},#{pwd})

测试

//增删改查需要提交事务
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //MAPPER.就是对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
         int res = mapper.addUser(new User(4,"哈哈哈","12333"));
        if(res>0)
        {
            System.out.println("插入成功");
        }
        sqlSession.commit();
        //关闭sql流对象
        sqlSession.close();
    }

update

编写接口

int updateUser(User user);

编写mapper中的sql语句


        update mybatis.user set name =#{name},pwd =#{pwd}  where id=#{id}

测试

@Test
    public void  updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(4,"HEHE","12345"));
        sqlSession.commit();

        sqlSession.close();
    }

Delete

编写接口

    //删除一个用户
    int deleteUser(int id);

编写mapper中的sql语句


        delete from mybatis.user where id =#{id};

测试

public void delteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }