Mybatis的增刪改查

DBAA12138發表於2020-12-21

Mybatis的增刪改查

1.介面

在介面中寫增、刪、改、查方法

    //根據id查詢使用者
    User getUserById(int id);

    //增加一個使用者
    int addUser(User user);

    //修改使用者
    int updateUser(User user);

    //刪除使用者
    int deleteUser(int id);

2.Mapper.xml

直接填寫sql語句

 <select id="getUserById" parameterType="int" resultType="com.zzt.pojo.User">
        select * from mybatis.user where id=#{id}
    </select>

<!--物件的屬性,可以直接取出來-->
    <insert id="addUser" parameterType="com.zzt.pojo.User" >
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>

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

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

3. Test測試類

需要提交事務sqlSession.commit();

 @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();
    }

    //增刪改查需要提交事務
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       mapper.addUser(new User(4,"哦吼","123"));

       //提交事務
        sqlSession.commit();
        sqlSession.close();
    }

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

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

    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(4);


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

相關文章