Mybatis-CRUD 学习案例

1.编写接口

package com.brock.mapper;

import com.brock.pojo.User;

import java.util.List;

public interface UserMapper {
    // 查询全部用户
    List<User> getUserList();

    //查询单个用户
    User getUser(int id);

    // 添加用户
    int addUser(User user);

    //修改用户信息
    int updateUser(User user);

    //删除用户
    int delUser(int id);
}

2.编写配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.brock.mapper.UserMapper">
    <!--查询全部用户-->
    <select id="getUserList" resultType="com.brock.pojo.User">
        select * from user;
    </select>
    <!-- 查询单个用户-->
    <select id="getUser" resultType="com.brock.pojo.User">
        select * from user where id = #{id};
    </select>
    <!-- 添加用户-->
    <insert id="addUser" parameterType="com.brock.pojo.User">
        insert into user (`name`,`pwd`) values (#{name},#{pwd});
    </insert>
    <!-- 删除用户-->
    <delete id="delUser" parameterType="int">
        delete from user where id = #{id};
    </delete>
</mapper>

3.编写测试代码

public class UserMapperTest {
    
    @Test
     //查询全部用户
    public void test(){
        SqlSession sqlSession = MybatisUntil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }

        sqlSession.close();
    }
    
    
    @Test
     // 查询单个用户
    public void getUser(){
        SqlSession sqlSession = MybatisUntil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUser(2);
        System.out.println(user);
        sqlSession.close();
    }
    
    
    @Test
    //添加用户
    public void addUser(){
        SqlSession sqlSession = MybatisUntil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int user = mapper.addUser(new User(4,"凌小龙","123456"));
        System.out.println(user);

        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUntil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int user = mapper.updateUser(new User(3,"小明","010101"));
        System.out.println(user);

        sqlSession.commit();
        sqlSession.close();
    }

    
    @Test
    //删除用户
    public void delUser(){
        SqlSession sqlSession = MybatisUntil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int user = mapper.delUser(4);
        System.out.println(user);

        sqlSession.commit();
        sqlSession.close();
    }
}

注意:

增删改必须开启事务否则无法成功进行操作;

4.错误排查

  • 标签不要匹配错
  • resource 绑定mapper ,需要使用路径!

  • 程序配置文件必须符合规范!

  • 空指针异常,没有注册到资源!

  • 输出的xml文件存在中文乱码

发表评论

邮箱地址不会被公开。 必填项已用*标注