mybatis学习-02-增删改查

mybatis学习-02-增删改查,第1张

mybatis学习-02-增删改查

总流程:
1.编写接口
2.编写对应的mapper中的sql语句
3.测试
1. namespace
namespace中的包名要和Dao/Mapper中的接口保持一致!
2. select
选择,查询语句:

id:就是对应的namespace中的方法名;resulType:sql语句执行的返回值!parameterType:参数类型
注意增删改需要提交事务

userMapper.java接口:

package com.zuo.dao;

import com.zuo.pojo.User;

import java.util.List;


public interface UserMapper {
    //查询全部用户
    List getUserList();
    //根据id查用户
    User getUserById(int id);
    //insert一个用户
    int addUser(User user);
    //修改用户
    int updateUser(User user);
    //删除一个用户
    int deleteUser(int id);
}

userMapper.xml接口对应的mapper


        

        select * from user where id = #{id}
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
        update user set name=#{name},pwd=#{pwd} where id= #{id}
        delete from user where id=#{id}



UserMapperTest.java测试:

package com.zuo.dao;

import com.zuo.pojo.User;
import com.zuo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;


public class UserMapperTest {
    @Test
    public void test(){
        //第一步:获取sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //方式一:getMapper执行sql
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List userList = userMapper.getUserList();
        for(User user: userList){
            System.out.println(user);
        }
        //关闭sqlSession
        sqlSession.close();
    }
    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int res = userMapper.addUser(new User(10, "afa", "123"));
        if(res>0) {
            System.out.println("插入成功!");
        }
        //提交事务
        sqlSession.commit();//提交事务
        sqlSession.close();
    }
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int res = mapper.updateUser(new User(10, "haha", "12345"));
        if(res>0) {
            System.out.println("修改成功!");
        }
        sqlSession.commit();//提交事务
        sqlSession.close();
    }
    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(10);
        sqlSession.commit();//提交事务
        sqlSession.close();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5719083.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存