欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > springboot-mybatisplus操作集锦(上)

springboot-mybatisplus操作集锦(上)

2024/10/28 3:18:21 来源:https://blog.csdn.net/dhrmt/article/details/143185099  浏览:    关键词:springboot-mybatisplus操作集锦(上)

springboot-mybatisplus操作集锦(上)


image-20241023145247477

一、编码

1.配置文件

spring:# 配置数据源信息datasource:# 配置数据源类型type: com.zaxxer.hikari.HikariDataSource# 配置连接数据库信息driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=falseusername: rootpassword: 123456

这个配置块的作用是让 Spring Boot 应用能够通过 HikariCP 连接到本地的 MySQL 数据库。配置正确后,就可以使用 MyBatis-Plus 进行数据库操作,简化 CRUD 代码并提高开发效率。

注意事项
  • 连接地址url MySQL5.7版本的url:

    jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false

    MySQL8.0版本的url:

    jdbc:mysql://localhost:3306/mybatis_plus? serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false

2.启动类

@SpringBootApplication
@MapperScan("com.lucifer.mybatisplus.mapper")
public class MybatisplusApplication {public static void main(String[] args) {SpringApplication.run(MybatisplusApplication.class, args);}
}

在Spring Boot启动类中添加@MapperScan注解,扫描mapper包

3.实体类

@Data //lombok注解
public class User {private Long id;private String name;private Integer age;private String email;
}

Lombok 是一个用于简化 Java 代码的库,通过注解的方式减少样板代码(boilerplate code)。常用的功能包括:

  • 自动生成 getters 和 setters。
  • 生成构造函数。
  • 提供 @Data@Builder@Value 等注解来简化类的定义。

4.mapper文件

public interface UserMapper extends BaseMapper<User> {
}

二、工具

1.显示日志

mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
image-20241023150301331

2.BaseMapper

以下是基于 BaseMapper 的 CRUD 操作教程,适用于使用 MyBatis 的项目。

1. 引入依赖

确保在你的 pom.xml 文件中添加 MyBatis 和相关依赖:

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version>
</dependency>

2. 创建实体类

定义一个实体类,例如 User

public class User {private Long id;private String name;private String email;// Getters and Setters
}

3. 创建 Mapper 接口

创建一个继承 BaseMapper 的接口,例如 UserMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;public interface UserMapper extends BaseMapper<User> {
}

4. 创建 Service 类

创建服务类以实现 CRUD 操作,例如 UserService

import com.baomidou.mybatisplus.extension.service.IService;public interface UserService extends IService<User> {
}

实现 UserService 接口:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic boolean save(User user) {return userMapper.insert(user) > 0;}@Overridepublic boolean removeById(Long id) {return userMapper.deleteById(id) > 0;}@Overridepublic User getById(Long id) {return userMapper.selectById(id);}@Overridepublic List<User> list() {return userMapper.selectList(null);}
}

5. 使用 Controller 处理请求

创建控制器类,例如 UserController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/users")
public class UserController {@Autowiredprivate UserService userService;@PostMappingpublic String createUser(@RequestBody User user) {userService.save(user);return "User created successfully!";}@GetMapping("/{id}")public User getUser(@PathVariable Long id) {return userService.getById(id);}@GetMappingpublic List<User> getAllUsers() {return userService.list();}@DeleteMapping("/{id}")public String deleteUser(@PathVariable Long id) {userService.removeById(id);return "User deleted successfully!";}
}

6. 配置 MyBatis

application.yml 中配置 MyBatis:

mybatis-plus:mapper-locations: classpath:/mappers/**/*.xmltypeAliasesPackage: com.example.model

7. 测试 CRUD 操作

你可以使用 Postman 或其他 API 测试工具进行以下操作:

  • 创建用户:发送 POST 请求到 /users,请求体为用户的 JSON 数据。

  • 获取用户:发送 GET 请求到 /users/{id}

  • 获取所有用户:发送 GET 请求到 /users

  • 删除用户:发送 DELETE 请求到 /users/{id}

8.与IService对比表

特性BaseMapperIService
定义基础数据访问层接口服务层接口,封装业务逻辑
功能提供基本的 CRUD 操作提供 CRUD 及其他业务操作
使用场景适合简单 CRUD 操作适合复杂业务逻辑
方法数量方法数量较少方法数量较多,包含业务方法
代码复杂度较低较高,需实现业务逻辑
扩展性扩展性有限扩展性强,可自定义业务逻辑
优点简单直接,易于使用逻辑清晰,易于维护
缺点缺乏业务逻辑管理增加了代码复杂度

三、常用注解

1. @TableName

指定实体类对应的表名。

@TableName("user")
public class User {private Long id;private String name;private Integer age;
}

这个示例中,User 实体类对应数据库中的 user 表。

2. @TableField

用于映射实体字段与数据库表字段,或指定字段属性(如忽略、加密等)。

@TableName("user")
public class User {private Long id;@TableField("username")private String name;@TableField(exist = false)private String extraField; // 该字段在数据库中不存在
}

name 字段在数据库中对应 username,而 extraField 字段不会映射到数据库中。

3. @IdType

指定主键生成策略。

@TableName("user")
public class User {@TableId(type = IdType.AUTO)private Long id;private String name;private Integer age;
}

id 字段的值由数据库自动生成,使用自增策略。

4. @Version

用于实现乐观锁。

@TableName("user")
public class User {private Long id;private String name;private Integer age;@Versionprivate Integer version;
}

在更新时,MyBatis-Plus 会根据 version 字段的值进行检查,确保数据没有被其他事务修改过。

5. @TableLogic

实现逻辑删除。设置后,执行删除操作时,不会真正删除记录,而是更新逻辑删除字段。

@TableName("user")
public class User {private Long id;private String name;private Integer age;@TableLogicprivate Integer deleted;
}

在此示例中,deleted 字段用于标记逻辑删除,0 表示未删除,1 表示已删除。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com