mybatis-plus 代码流程编写
使用swagger接口测试 创建springboot项目 添加相关依赖 sql文件编写 实体类编写 相关配置文件的编写 编写业务逻辑 测试
创建springboot-mybatis-plus项目
项目目录
添加相关依赖
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
sql文件编写
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
`birthday` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `tb_user` VALUES (1, 'zhangsan', '123456', '张三', 18, 'test1@yh.cn', '2019-09-26 11:42:01');
INSERT INTO `tb_user` VALUES (2, 'lisi', '123456', '李四', 20, 'test2@yh.cn', '2019-10-01 11:42:08');
INSERT INTO `tb_user` VALUES (3, 'wangwu', '123456', '王五', 28, 'test3@yh.cn', '2019-10-02 11:42:14');
INSERT INTO `tb_user` VALUES (4, 'zhaoliu', '123456', '赵六', 21, 'test4@yh.cn', '2019-10-05 11:42:18');
INSERT INTO `tb_user` VALUES (5, 'sunqi', '123456', '孙七', 24, 'test5@yh.cn', '2019-10-14 11:42:23');
INSERT INTO `tb_user` VALUES (8, 'string', 'string', 'string', 10, 'string', '2021-09-04 02:56:37');
SET FOREIGN_KEY_CHECKS = 1;
实体类编写
@Data
@TableName("tb_user")
public class TbUser implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
private LocalDateTime birthday;
}
相关配置文件的编写
mybatis-plus配置文件
@EnableAutoConfiguration
@Configuration
public class MyBatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
WebMvcConfig配置文件
@Component
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Swagger配置文件
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.lifly.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo buildApiInfo() {
Contact contact = new Contact("lifly", "", "");
return new ApiInfoBuilder()
.title("mybatis-plus测试文档")
.description("")
.contact(contact)
.version("1.0.0").build();
}
}
application.yml配置文件
server:
port: 10086
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/huiminpay_merchant_service?useUnicode=true&useSSL=false
username: root
password: 1234
mybatis-plus:
type-aliases-package: com.lifly.bean
mapper-locations: classpath:/mapper/*.xml
logging:
level:
com.lifly.mapper: debug
编写业务逻辑
mapper文件
@Repository
public interface UserMapper extends BaseMapper<TbUser> {
}
service接口与实现类
接口
public interface TbUserService {
public int insert(TbUser tbUser);
int deleteById(Long id);
int deleteByMap(TbUser tbUser);
int deleteByIds(List ids);
int update(TbUser tbUser);
int updateById(TbUser tbUser);
TbUser selectById(Long id);
TbUser selectOne(TbUser tbUser);
List<TbUser>selectBatchIds(List ids);
List<TbUser>selectPage(long current, long size);
int selectCount();
List<TbUser>selectList();
List<TbUser>selectEqList(TbUser tbUser);
List<TbUser>selectLikeList(TbUser tbUser);
List<TbUser> selectLike(TbUser tbUser);
}
实现类
@Service
public class TbUserServiceImpl implements TbUserService {
@Autowired
private UserMapper userMapper;
@Override
public int insert(TbUser tbUser) {
TbUser user = new TbUser();
user.setId(tbUser.getId());
user.setAge(tbUser.getAge());
user.setEmail(tbUser.getEmail());
user.setName(tbUser.getName());
user.setPassword(tbUser.getPassword());
user.setUserName(tbUser.getUserName());
String s = DateUtil.toDateTime(tbUser.getBirthday());
user.setBirthday(tbUser.getBirthday());
int insert = userMapper.insert(user);
return insert;
}
@Override
public int deleteById(Long id) {
return userMapper.deleteById(id);
}
@Override
public int deleteByMap(TbUser tbUser) {
QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
if (tbUser.getId() != null){
wrapper.eq("id",tbUser.getId());
}
if (tbUser.getUserName() != null){
wrapper.eq("user_name",tbUser.getUserName());
}
if (tbUser.getPassword() != null){
wrapper.eq("password",tbUser.getPassword());
}
if (tbUser.getName() != null){
wrapper.eq("name",tbUser.getName());
}
if (tbUser.getAge() != null){
wrapper.eq("age",tbUser.getAge());
}
if (tbUser.getEmail() != null){
wrapper.eq("email",tbUser.getEmail());
}
if (tbUser.getBirthday() != null){
wrapper.eq("birthday",tbUser.getBirthday());
}
return userMapper.delete(wrapper);
}
@Override
public int deleteByIds(List ids) {
return userMapper.deleteBatchIds(ids);
}
@Override
public int update(TbUser tbUser) {
TbUser user = new TbUser();
user.setAge(tbUser.getAge());
user.setEmail(tbUser.getEmail());
user.setName(tbUser.getName());
user.setPassword(tbUser.getPassword());
user.setUserName(tbUser.getUserName());
String s = DateUtil.toDateTime(tbUser.getBirthday());
user.setBirthday(tbUser.getBirthday());
QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
wrapper.eq("id",tbUser.getId());
return userMapper.update(tbUser,wrapper);
}
@Override
public int updateById(TbUser tbUser) {
return userMapper.updateById(tbUser);
}
@Override
public TbUser selectById(Long id) {
return userMapper.selectById(id);
}
@Override
public TbUser selectOne(TbUser tbUser){
QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
if (tbUser.getId()!=null ) {
wrapper.eq("id", tbUser.getId());
}
return userMapper.selectOne(wrapper);
}
@Override
public List<TbUser> selectBatchIds(List ids) {
return userMapper.selectBatchIds(ids);
}
@Override
public List<TbUser> selectPage(long current, long size) {
QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
Page<TbUser> page = new Page<>(current, size);
System.out.println("当前页码:"+current);
System.out.println("显示的条数:"+size);
IPage<TbUser> userIPage = userMapper.selectPage(page, wrapper);
System.out.println("总页数:"+userIPage.getPages());
System.out.println("总总记录数数:"+userIPage.getTotal());
List<TbUser> records = userIPage.getRecords();
for (TbUser record : records) {
System.out.println(record);
}
return records;
}
@Override
public int selectCount() {
QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
return userMapper.selectCount(wrapper);
}
@Override
public List<TbUser> selectList() {
QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
return userMapper.selectList(wrapper);
}
@Override
public List<TbUser> selectEqList(TbUser tbUser) {
QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
wrapper.eq("password",tbUser.getPassword())
.ge("age",tbUser.getAge());
return userMapper.selectList(wrapper);
}
@Override
public List<TbUser> selectLikeList(TbUser tbUser) {
QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
if (tbUser.getId()!=null){
wrapper.like("id",tbUser.getId());
}
if (tbUser.getBirthday()!=null){
wrapper.like("birthday",tbUser.getBirthday());
}
if (tbUser.getAge()!=null){
wrapper.like("age",tbUser.getAge());
}
if (tbUser.getEmail()!=null){
wrapper.like("email",tbUser.getEmail());
}
if (tbUser.getName()!=null){
wrapper.like("name",tbUser.getName());
}
if (tbUser.getPassword()!=null){
wrapper.like("password",tbUser.getPassword());
}
if (tbUser.getUserName()!=null){
wrapper.like("user_name",tbUser.getUserName());
}
return userMapper.selectList(wrapper);
}
@Override
public List<TbUser> selectLike(TbUser tbUser) {
LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
if (tbUser.getId()!=null){
wrapper.like(TbUser::getId,tbUser.getId());
}
if (tbUser.getBirthday()!=null){
wrapper.like(TbUser::getBirthday,tbUser.getBirthday());
}
if (tbUser.getAge()!=null){
wrapper.like(TbUser::getAge,tbUser.getAge());
}
if (tbUser.getEmail()!=null){
wrapper.like(TbUser::getEmail,tbUser.getEmail());
}
if (tbUser.getName()!=null){
wrapper.like(TbUser::getName,tbUser.getName());
}
if (tbUser.getPassword()!=null){
wrapper.like(TbUser::getPassword,tbUser.getPassword());
}
if (tbUser.getUserName()!=null){
wrapper.like(TbUser::getUserName,tbUser.getUserName());
}
return userMapper.selectList(wrapper);
}
}
controller控制器
@Api(value = "用户接口API接口",description = "主要实现了用户的增删改查等操作")
@RestController
@RequestMapping("/user")
public class TbUserController {
@Autowired
private TbUserService tbUserService;
@ApiOperation("用户添加")
@PostMapping("/insert")
public int insert(@RequestBody TbUser tbUser){
return tbUserService.insert(tbUser);
}
@ApiOperation("根据id删除用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value="主键ID",dataType = "long",required = true)
})
@GetMapping("/delete/{id}")
public int deleteById(@PathVariable("id") Long id){
return tbUserService.deleteById(id);
}
@ApiOperation("根据实体类条件删除用户")
@GetMapping("/deleteByMap/")
public int deleteByMap(TbUser tbUser){
return tbUserService.deleteByMap(tbUser);
}
@ApiOperation("根据id批量删除")
@GetMapping("/deleteByIds/{ids}")
public int deleteByIds(@PathVariable("ids") List<Long>ids){
return tbUserService.deleteByIds(ids);
}
@ApiOperation("更新数据")
@PostMapping("/update/")
public int update(@RequestBody TbUser tbUser){
return tbUserService.update(tbUser);
}
@ApiOperation("根据id更新数据")
@PostMapping("/deleteById/")
public int deleteById(@RequestBody TbUser tbUser){
return tbUserService.updateById(tbUser);
}
@ApiOperation("根据id查询数据")
@GetMapping("/selectById/{id}")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value="主键ID",dataType = "long",required = true)
})
public TbUser selectById(@PathVariable("id") Long id){
return tbUserService.selectById(id);
}
@ApiOperation("根据entity条件,查询一条记录")
@GetMapping("/selectOne/")
public TbUser selectOne(TbUser tbUser){
return tbUserService.selectOne(tbUser);
}
@ApiOperation("根据id集合查询数据")
@GetMapping("/selectBatchIds/{ids}")
public List<TbUser> selectBatchIds(@PathVariable("ids") List ids){
return tbUserService.selectBatchIds(ids);
}
@ApiOperation("分页查询")
@ApiImplicitParams({
@ApiImplicitParam(name = "current",value = "当前页",dataType = "long",required = true),
@ApiImplicitParam(name="size",value = "显示的总数",dataType = "long",required = true)
})
@GetMapping("/selectPage/{current}/{size}")
public List<TbUser>selectPage(@PathVariable("current") long current,
@PathVariable("size") long size){
return tbUserService.selectPage(current,size);
}
@ApiOperation("查询总记录数")
@GetMapping("/selectCount")
public Integer selectCount(){
Integer i = tbUserService.selectCount();
System.out.println(i);
return i;
}
@ApiOperation("查询所有记录")
@GetMapping("/selectList")
public List<TbUser>selectList(){
return tbUserService.selectList();
}
@ApiOperation("查询密码是?年龄大于?")
@GetMapping("/selectEqList/")
public List<TbUser>selectEqList(TbUser tbUser){
return tbUserService.selectEqList(tbUser);
}
@ApiOperation("模糊查询")
@GetMapping("/selectLikeList/")
public List<TbUser>selectLikeList(TbUser tbUser){
return tbUserService.selectLikeList(tbUser);
}
@ApiOperation("lambda实现模糊查询")
@GetMapping("selectLike/")
public List<TbUser>selectLike(TbUser tbUser){
return tbUserService.selectLike(tbUser);
}
}
启动类
@SpringBootApplication
@MapperScan("com.lifly.mapper")
public class MybatisPlus {
public static void main(String[] args) {
SpringApplication.run(MybatisPlus.class,args);
}
}
最终运行启动类,直接访问localhost:10086/swagger-ui.html即可 最终的访问界面如下图所示 整个项目我会放到gitee上,https://gitee.com/doublelifly/mybatis-plus-project,同时也会上传到csdn上仅供学习,不作其它用途
|