当前位置:   article > 正文

springboot + mybatis-plus 实现增删改查_springbootmybatisplus增删改查

springbootmybatisplus增删改查

一. 添加依赖

  1. <!-- MySQL驱动 -->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <scope>runtime</scope>
  6. </dependency>
  7. <!-- mybatis-plus启动器 -->
  8. <dependency>
  9. <groupId>com.baomidou</groupId>
  10. <artifactId>mybatis-plus-boot-starter</artifactId>
  11. <version>3.5.1</version>
  12. </dependency>
  13. <!-- 代码生成器 -->
  14. <dependency>
  15. <groupId>com.baomidou</groupId>
  16. <artifactId>mybatis-plus-generator</artifactId>
  17. <version>3.5.2</version>
  18. </dependency>
  19. <!-- 模板引擎 -->
  20. <dependency>
  21. <groupId>org.freemarker</groupId>
  22. <artifactId>freemarker</artifactId>
  23. <version>2.3.29</version>
  24. </dependency>
  25. <!-- 校验工具 -->
  26. <dependency>
  27. <groupId>javax.validation</groupId>
  28. <artifactId>validation-api</artifactId>
  29. <version>2.0.1.Final</version>
  30. </dependency>
  31. <!-- lombok -->
  32. <dependency>
  33. <groupId>org.projectlombok</groupId>
  34. <artifactId>lombok</artifactId>
  35. <optional>true</optional>
  36. </dependency>

二. 配置application.properties文件

  1. server.port=9800
  2. #dbname为具体连接的数据库名
  3. spring.datasource.url=jdbc:mysql://localhost:3306/dbname?&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
  4. spring.datasource.username=root
  5. spring.datasource.password=123456
  6. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  7. #上传文件大小限制
  8. spring.servlet.multipart.max-file-size=10000MB
  9. spring.servlet.multipart.max-request-size=10000MB
  10. #xml文件存放位置为resources目录下新建mapper文件夹
  11. mybatis-plus.global-config.db-config.logic-delete-field=isDeleted
  12. mybatis-plus.mapper-locations=classpath:mapper/*.xml
  13. mybatis-plus.type-aliases-package=com.example.collection.dao

三. 代码实现

        1. 新建mybatis-plus配置文件MybatisPlusConfig

  1. @Configuration
  2. @MapperScan("com.example.collection.dao")
  3. public class MybatisPlusConfig {
  4. @Bean
  5. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  6. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  7. // 分页插件
  8. interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
  9. // 乐观锁插件
  10. interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
  11. return interceptor;
  12. }
  13. }

其中mapper文件存放在dao文件夹下

        2. 新建统一返回类CommonResult

  1. public class CommonResult<T> {
  2. private T data;
  3. private String msg;
  4. private Integer code;
  5. public CommonResult() {
  6. }
  7. public CommonResult(T data) {
  8. this.data = data;
  9. this.msg = "success";
  10. this.code = 200;
  11. }
  12. public CommonResult(T data, String msg, Integer code) {
  13. this.data = data;
  14. this.msg = msg;
  15. this.code = code;
  16. }
  17. public T getData() {
  18. return data;
  19. }
  20. public void setData(T data) {
  21. this.data = data;
  22. }
  23. public String getMsg() {
  24. return msg;
  25. }
  26. public void setMsg(String msg) {
  27. this.msg = msg;
  28. }
  29. public Integer getCode() {
  30. return code;
  31. }
  32. public void setCode(Integer code) {
  33. this.code = code;
  34. }
  35. }

       3. 新建User类及PageParam分页类

  1. @TableName(value = "user", autoResultMap = true)
  2. public class User {
  3. private Long id;
  4. private String account;
  5. private String username;
  6. private String password;
  7. //get&set...
  8. }
  1. public class PageParam {
  2. @ApiModelProperty("当前页, 默认1")
  3. private long current = 1;
  4. @ApiModelProperty("每页显示条数,默认10")
  5. private long size = 10;
  6. @ApiModelProperty("正序排列字段,多个以逗号隔开")
  7. private String ascs;
  8. @ApiModelProperty("反序排列字段,多个以逗号隔开")
  9. private String descs;
  10. /**
  11. * 将分页参数转换成Page
  12. *
  13. * @param <T> 实体类型
  14. * @return Page
  15. */
  16. public <T> Page<T> toPage() {
  17. Page<T> page = new Page<>();
  18. page.setCurrent(this.getCurrent());
  19. page.setSize(this.getSize());
  20. if (StrUtil.isNotBlank(this.getAscs())) {
  21. page.addOrder(OrderItem.ascs(this.getAscs().split(",")));
  22. }
  23. if (StrUtil.isNotBlank(this.getDescs())) {
  24. page.addOrder(OrderItem.descs(this.getDescs().split(",")));
  25. }
  26. return page;
  27. }
  28. //set&get...
  29. }

        4. Dao层及其实现

                1.在dao目录下新建文件

  1. public interface UserMapper extends BaseMapper<User> {
  2. }

                2.在resources目录下新建mapper文件夹,其中存放对应的xml文件。

                      其中命名空间namespace一定要准确对应mapper文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.collection.dao.UserMapper">
  4. </mapper>

           5. Service层及其实现

  1. public interface UserService extends IService<User> {
  2. void removeUser(List<Long> ids);
  3. IPage<User> pageUser(PageParam page, String account);
  4. }
  1. @Service
  2. public class UserImpl extends ServiceImpl<UserMapper, User> implements UserService {
  3. @Override
  4. public void removeUser(List<Long> ids) {
  5. for (Long id: ids) {
  6. lambdaUpdate()
  7. .eq(User::getId, id)
  8. .remove();
  9. }
  10. }
  11. @Override
  12. public IPage<User> pageUser(PageParam page, String account) {
  13. return this.lambdaQuery()
  14. .eq(StrUtil.isNotEmpty(account), User::getAccount, account)
  15. .page(page.toPage());
  16. }
  17. }

            6. Controller层及其实现

  1. @RestController
  2. @RequestMapping("/user")
  3. @CrossOrigin(value = "*", maxAge = 3600)
  4. public class UserController {
  5. @Resource
  6. private UserService server;
  7. //用户注册
  8. @RequestMapping(value = "/register", method = RequestMethod.POST)
  9. public CommonResult<String> saveUser(@RequestBody User user) {
  10. //在数据库中将account字段设置为unique,不允许字段值重复
  11. try {
  12. server.save(user);
  13. return new CommonResult<>("创建成功");
  14. } catch (Exception e) {
  15. return new CommonResult<>("创建失败,账号已存在", "Bad Request",400);
  16. }
  17. }
  18. //查询用户列表(可以传入account精准查询或不传account批量查询)
  19. @RequestMapping(value = "/query", method = RequestMethod.GET)
  20. public CommonResult queryUserList(
  21. PageParam page,
  22. @RequestParam(required = false, value = "account") String account) {
  23. return new CommonResult(server.getUserList(page, account));
  24. }
  25. //删除用户
  26. @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
  27. public CommonResult removeUser(@RequestBody List<String> ids) {
  28. server.removeUser(ids);
  29. return new CommonResult("成功删除", "Delete Failed", 200);
  30. }
  31. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/598292
推荐阅读
相关标签
  

闽ICP备14008679号