Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1、pom.xml引入MyBatis Plus的jar,覆盖Spring Mybatis
<!--Mybatis-->
<!--这里是 Mybatis—plus jar ↓↓ ↓↓↓ ↓↓↓-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
2、修改application.yml文件
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
type-aliases-package: com.example.demo.entity
3、开启AR功能(ActiveRecord)领域模型
3.1、实体类开启AR (同时开启Dao层AR)
继承MP特殊类Model<> 泛型:当前实体类
@Component
public class Student extends Model<Student> {
@TableId(value = "id", type = IdType.AUTO)
private int id;
@TableField("name")
private String name;
@TableField("sex")
private String sex;
@TableField("classname")
private String classname;
@Override
protected Serializable pkVal() {
return this.id;
}
}
3.2、Dao层开启AR
继承MP特殊类BaseMapper<> 泛型:当前实体类
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
public List<Student> getAll();
public Student getStudentById();
}
4、最后就是Service 开启AR
4.1、Service层 接口 interface
继承MP特殊类IService<> 泛型:当前实体类
public interface IStudent extends IService<Student> {
public List<Student> getAll();
public Student getStudentById();
}
4.1、Service层 实现 implement
继承MP特殊类ServiceImpl<mapper,实体类>
@Service
public class StudentImpl extends ServiceImpl<StudentMapper,Student> implements IStudent {
@Autowired
StudentMapper studentMapper;
public Student getStudentById() {
Student student = studentMapper.selectById("1710272147");
return student;
}
@Override
public List<Student> getAll() {
List<Student> students = studentMapper.getAll();
return students;
}
}
4.2、这时候就可以调用许多AR 内置的方法了(附带一张效果图)
5、Controller层 不做修改,
@Controller
public class HelloController {
@Autowired
private IStudent iStudent;
@RequestMapping("/selectStudentById")
@ResponseBody
public Student selectStudentById() {
Student student = iStudent.getStudentById();
return student;
}
}
6、运行程序入口 访问地址
帅小伙的信息就查询出来了