Mybatis-plus
MyBatis-Plus
用Mybatid-plus实现增删改查
1.将StudentMapper接口继承BaseMapper,将拥有了BaseMapper中的所有方法:
public interface StudentMapper extends BaseMapper {
}
2.编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("students")//表名
public class Student {
private String stuNum;
private String stuName;
private String stuGender;
private int stuAge;
}
3.编写StudentMapper对应的xml文件
<?xml version="1.0" encoding="UTF-8" ?>
4.在数据库xml中配置StudentMapper.xml
5.使用MP中的MybatisSqlSessionFactoryBuilder进程构建,编写测试类
public class TestMybatis_plus {
@Test
public void testStudent() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List students = mapper.selectList(null);
for (Student student:students
) {
System.out.println(student);
}
}
}
6.测试结果

7.出现的问题
7.1 table不存在
解决:在实体类上注解表名@TableName("students")
7.2 Unknowncolumn字段名infieldlist
解决:实体类名与数据库字段名不匹配
7.3 运行成功,但查询返回null
解决:在数据库中,如果存在字段为xx_xx之类的,在实现映射成实例的时候就要求实例的属性为驼峰标识,比如:xxXx,
也可以添加注解@TableField(数据库字段名)。
例:stu_num在实体类中写为stuNum
8.测试增删改
8.1.1添加数据
```java
//添加数据
@Test
public void testInsertStudent() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession(true);//ture为默认提交事务
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student("2021005", "文文", "女", 18);
mapper.insert(student);
}
8.1.2结果
8.2.1查询特定数据
//查询带有特定条件的数据
@Test
public void testPartStudent() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.like("stu_gender", "男");
List student = mapper.selectList(queryWrapper);
for (Student s:student
) {
System.out.println(s);
}
}
8.2.2结果
8.3.1 删除数据
//删除数据
@Test
public void testDelStudent() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession(true);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.deleteById(2021005);
}
8.3.2找不到数据库中的ID
解决:
@TableId(type = IdType.AUTO)//告诉下面的字段为id
private String stuNum;