Mybatis的基本增删改查(代码)

3、CRUD增删改查

3.1、namespace

namespace中的包名要和Mapper接口的包名一致

3.2、select

选择、查询语句;

  • id就是对应的namespace中的方法名;
  • resultType:sql语句执行的返回值!
  • parameterType:参数类型!

1、编写接口

 //获取全部用户
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);

2、编写对应的Mapper中的SQL语句


    <select id="getUserList" resultType="com.maple.pojo.User">
        select * from opo.user
    select>

    
    <select id="getUserById" resultType="com.maple.pojo.User" parameterType="int">
        select * from user WHERE id=#{id}
    select>

3、测试

    @Test
    public void test(){
        //第一步获取sqlSession对象
         SqlSession sqlSession = MybatisUtils.getSqlSession();
        //方式一:getMapper

        UserMapper userDao = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userDao.getUserList();
        //方式二:
//        List userList = sqlSession.selectList("com.maple.dao.UserDao.getUserList");
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);

        sqlSession.close();


    }

3.3、Insert

<insert id="addUser" parameterType="com.maple.pojo.User">
        INSERT into user (id,name,password,email,birthday) VALUES (#{id},#{name},#{password},#{email},#{birthday});
    insert>

3.4、update

<update id="updateUser" parameterType="com.maple.pojo.User">
        update user set name=#{name},password=#{password},email=#{email},birthday=#{birthday}   where id=#{id} ;
    update>

3.5、Delete

<delete id="deleteUser" parameterType="int">
        delete FROM user WHERE id=#{id};
    delete>

注意点:增删改需要提交事务!

你可能感兴趣的:(Mybatis的基本增删改查(代码))