使用mapper代理对象实现增删改查

本文展示了如何在MyBatis中通过SqlSessionFactory创建SqlSession,并利用SqlSession获取Mapper代理对象,进行增删改查操作。具体包括获取所有数据、添加数据、删除数据、更新数据以及不同方式的模糊查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class TestStudentMapper {

SqlSessionFactory factory;

@Before

public void init(){

try {

InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");

SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();

factory = sfb.build(in);

} catch (IOException e) {

e.printStackTrace();

}

}

@Test

public void test01(){

//开启事务自动提交

SqlSession sqlSession = factory.openSession(true);

//获取dao层的代理对象

StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

List<Student> students = studentDao.getAll();

students.forEach(student -> System.out.println(student));

}

@Test

public void test02(){ //添加数据

SqlSession sqlSession = factory.openSession(true);

Student student = Student.builder().stuSex("男").stuNo("2021073100").stuName("李四").stuBirth(new Date()).build();

StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

Integer line = studentDao.addOne(student);

System.out.println(line);

}

@Test

public void test03(){//删除一条数据

SqlSession sqlSession = factory.openSession(true);

StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

Integer line = studentDao.delOne("李四");

System.out.println(line);

}

@Test

public void test04() { //修改数据

SqlSession sqlSession = factory.openSession(true);

StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

Student student = Student.builder().stuSex("女").stuNo("2021073100").stuName("李四").stuBirth(new Date()).build();

Integer line = studentDao.updateOne(student);

System.out.println(line);

}

@Test

public void test06(){//模糊查询一个学生信息 一个参数

SqlSession sqlSession = factory.openSession(true);

StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

List<Student> students = studentDao.selectLikeName("li");

System.out.println(students.toString());

}

@Test

public void test07(){//模糊查询一个学生信息 两个参数

SqlSession sqlSession = factory.openSession(true);

StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

List<Student> students = studentDao.selectLikeName2("li", "2021072902");

System.out.println(students.toString());

}

@Test

public void test08(){//模糊查询一个学生信息 一个集合参数 mapper文件中按照key取值

SqlSession sqlSession = factory.openSession(true);

StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

HashMap<String, String> map = new HashMap<>();

map.put("stuname","li");

map.put("stuno", "2021072902");

List<Student> students = studentDao.selectLikeName3(map);

System.out.println(students.toString());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值