集成mybatis-plus依赖
官网 : https://baomidou.com/
pom.xml
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
MybatisPlusConfig.java
config里新建Mybatis分页配置
package com.zj.demo.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.zj.demo.mapper")
public class MybatisPlusConfig {
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
错误示例
集成Swagger-Ui
访问地址:http://localhost:9090/swagger-ui/index.html
Pom.xml:
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
SwaggerConfig.java
package com.zj.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
*
* @return
*/
@Bean
public Docket restApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("标准接口")
.apiInfo(apiInfo("Spring Boot中使用Swagger2构建RESTful APIs", "1.0"))
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.zj.demo.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://ip:port/swagger-ui.html
*
* @return
*/
private ApiInfo apiInfo(String title, String version) {
return new ApiInfoBuilder()
.title(title)
.description("更多请关注: https://blog.csdn.net/xqnode")
.termsOfServiceUrl("https://blog.csdn.net/xqnode")
.contact(new Contact("xqnode", "https://blog.csdn.net/xqnode", "xiaqingweb@163.com"))
.version(version)
.build();
}
}
集成后的项目代码
UserMapper.java
package com.zj.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zj.demo.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
//@Mapper
public interface UserMapper extends BaseMapper<User> {
// @Select("SELECT * from sys_user")
// List<User> findAll();
//
// @Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
// " #{nickname}, #{email},#{phone}, #{address})")
// int insert(User user);
//
// int update(User user);
//
// @Delete("delete from sys_user where id = #{id}")
// Integer deleteById(@Param("id") Integer id);
//
// @Select("select * from sys_user where username like #{username} limit #{pageNum}, #{pageSize}")
// List<User> selectPage(Integer pageNum, Integer pageSize, String username);
//
// @Select("select count(*) from sys_user where username like concat('%', #{username}, '%') ")
// Integer selectTotal(String username);
}
UserController.java
package com.zj.demo.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zj.demo.entity.User;
import com.zj.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
// 新增和修改
@PostMapping
public boolean save(@RequestBody User user) {
// 新增或者更新
return userService.saveUser(user);
}
// 查询所有数据
@GetMapping
public List<User> findAll() {
return userService.list();
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return userService.removeById(id);
}
// 分页查询
// 接口路径:/user/page?pageNum=1&pageSize=10
// @RequestParam接受
// limit第一个参数 = (pageNum - 1) * pageSize
// pageSize
// @GetMapping("/page")
// public Map<String, Object> findPage(@RequestParam Integer pageNum,
// @RequestParam Integer pageSize,
// @RequestParam String username) {
// pageNum = (pageNum - 1) * pageSize;
// username = "%" + username + "%";
// List<User> data = userMapper.selectPage(pageNum, pageSize, username);
// Integer total = userMapper.selectTotal(username);
// Map<String, Object> res = new HashMap<>();
// res.put("data", data);
// res.put("total", total);
// return res;
// }
// 分页查询 - mybatis-plus的方式
@GetMapping("/page")
public IPage<User> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String username,
@RequestParam(defaultValue = "") String nickname,
@RequestParam(defaultValue = "") String address) {
IPage<User> page = new Page<>(pageNum, pageSize);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if (!"".equals(username)) {
queryWrapper.like("username", username);
}
if (!"".equals(nickname)) {
queryWrapper.like("nickname", nickname);
}
//和上面的if判断效果一样
queryWrapper.like(!address.equals(""),"address", address);
return userService.page(page, queryWrapper);
}
}
User.java
package com.zj.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@Data
@TableName(value = "sys_user")
public class User {
@TableId(type = IdType.AUTO)
private Integer id;
private String username;
@JsonIgnore
private String password;
private String nickname;
private String email;
private String phone;
private String address;
@TableField(value = "avatar_url") // 指定数据库的字段名称
private String avatar;
}
application.yml
server:
port: 9090
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/joyce?serverTimezone=GMT%2b8
username: root
password: 123456
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
mybatis:
mapper-locations: classpath:mapper/*.xml #扫描所有mybatis的xml文件
# configuration:
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
SpringbootApplication.java
package com.zj.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
//@EnableCaching
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
注意事项
mybatis-plus在绑定数据库与实体类的注意点
表名@TableName
mybatis-plus默认实体类名为表名如果你的实体类【User】跟表名【sys_user】不一致,mybatis-plus会查不到表,报错
所以需要在entity声明的时候绑定表名
主键 @TableId
此外,主键需要加一个@TableId注解声明其数据库内的名称以及类型
其他字段 @TableField
其他字段的别名绑定使用@TableField
此外Mybatis-Plus会自动转化驼峰
avatarUrl === avatar_url
Swagger版本与SpringBoot高版本会冲突
解决办法
这里是在yaml里添加了这个配置
spring:
mvc:
pathmatch:
matching-strategy:
```