一、新建一个spring boot项目
如何在idea中创建一个SpringBoot项目(超详细教学)_我是老伯的博客-CSDN博客
二、建立分层包
添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
1. config层 MybatisPlusConfig.java ??
集成完毕分页插件之后,可去掉PageHelper 分页插件
@Configuration
public class MybatisPlusConfig {
// 最新版
@Bean // <bean id=""/>
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
2. entity层 Student.java
@Data
public class Student {
private Long id;
private String name;
private String number;
}
3.mapper层 StudentMapper.java
public interface StudentMapper extends BaseMapper<Student> {
}
4.service层 Impl包下StudentServiceImpl.java
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
}
StudentService.java
public interface StudentService extends IService<Student> {
}
mybatis plus配置
application.yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/qcby_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=CTT
username: root
password: 密码
driver-class-name: com.mysql.cj.jdbc.Driver
# mybatis-plus配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
typeAliasesPackage: com.qcby.zsgc.entity
mapperLocations: classpath:mapper/*.xml
# 全局配置id自增
global-config:
db-config:
id-type: auto
pagehelper:
helperDialect: mysql
reasonable: true # 修改默认值
5. controller层 Studentcontroller.java
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("save")
public void save(Student student){
studentService.save(student);
}
@RequestMapping("update")
public void update(Student student) {
studentService.updateById(student);
}
@RequestMapping("saveOrUpdate")
public void saveOrUpdate(Student student){
studentService.saveOrUpdate(student);
}
@RequestMapping("removeById")
public void removeById(Long id) {
studentService.removeById(id);
}
@RequestMapping("list")
public List<Student> list(Long id) {
return studentService.list();
}
/**
* 查询条件 =》name得模糊查询 和 number精确匹配 可选的
* @param pageNo
* @param pageSize
* @return
*/
@RequestMapping("listPage")
public Page<Student> listPage(Integer pageNo,Integer pageSize){
Page<Student> page =new Page(pageNo,pageSize);
return studentService.page(page);
}
}
?添加模糊查询和精确查询
@RequestMapping("listPage")
public Page<Student> listPage(Integer pageNo,Integer pageSize,Student student){
//处理分页
Page<Student> page =new Page(pageNo,pageSize);
//帮助我们拼接where
QueryWrapper<Student> queryWrapper = new QueryWrapper();
if(!StringUtils.isEmpty(student.getName())){
queryWrapper.like("name",student.getName());
}
if (!StringUtils.isEmpty(student.getNumber())) {
queryWrapper.eq("numner",student.getNumber());
}
//添加分页 和查询条件
return studentService.page(page,queryWrapper);
}
|