您的位置:首页 > 健康 > 养生 > 赤壁网站建设公司_美食网页设计模板中文_广告联盟平台_google seo 优化

赤壁网站建设公司_美食网页设计模板中文_广告联盟平台_google seo 优化

2025/4/17 21:35:34 来源:https://blog.csdn.net/weixin_62922042/article/details/147011740  浏览:    关键词:赤壁网站建设公司_美食网页设计模板中文_广告联盟平台_google seo 优化
赤壁网站建设公司_美食网页设计模板中文_广告联盟平台_google seo 优化

本文将演示如何在Spring Boot项目中整合MyBatis-Plus框架,快速实现数据库的增删改查操作。相较于原生MyBatis,MyBatis-Plus提供了更简洁的API和自动化功能。


环境准备

  • JDK 1.8+
  • MySQL 5.7+
  • Spring Boot 2.7.x
  • MyBatis-Plus 3.5.x

实现步骤

1. 创建项目并添加依赖

通过Spring Initializr创建项目时勾选:

  • Spring Web
  • MySQL Driver

手动添加MyBatis-Plus依赖(pom.xml):

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version>
</dependency>

2. 配置数据库连接(application.yml)

spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mp_demo?useSSL=false&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开启SQL日志global-config:db-config:id-type: assign_id # 主键生成策略(使用雪花算法)

3. 创建实体类

@Data
@TableName("t_user") // 指定表名
public class User {@TableId(type = IdType.ASSIGN_ID) // 雪花算法生成IDprivate Long id;private String username;private Integer age;private String email;
}

4. 创建Mapper接口

@Mapper
public interface UserMapper extends BaseMapper<User> {// 继承BaseMapper后已包含基础CRUD方法
}

5. 实现Service层(可选增强)

@Service
public class UserService {@Autowiredprivate UserMapper userMapper;// 插入public int addUser(User user) {return userMapper.insert(user);}// 查询全部public List<User> getAllUsers() {return userMapper.selectList(null);}// 条件查询public User getUserById(Long id) {return userMapper.selectById(id);}// 更新public int updateUser(User user) {return userMapper.updateById(user);}// 删除public int deleteUser(Long id) {return userMapper.deleteById(id);}
}

6. 添加分页插件配置

@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
}

7. 创建Controller

@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMappingpublic String add(@RequestBody User user) {userService.addUser(user);return "插入成功";}@GetMapping("/{id}")public User getById(@PathVariable Long id) {return userService.getUserById(id);}@GetMapping("/list")public List<User> list() {return userService.getAllUsers();}@PutMappingpublic String update(@RequestBody User user) {userService.updateUser(user);return "更新成功";}@DeleteMapping("/{id}")public String delete(@PathVariable Long id) {userService.deleteUser(id);return "删除成功";}
}

测试示例

插入数据(POST /user)

{"username": "张三","age": 25,"email": "zhangsan@example.com"
}

分页查询(需自定义方法)

// 在Mapper中添加:
@Select("SELECT * FROM t_user WHERE age > #{age}")
Page<User> selectPageByAge(Page<User> page, @Param("age") Integer age);// Controller调用:
@GetMapping("/page")
public Page<User> page(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize) {Page<User> page = new Page<>(pageNum, pageSize);return userMapper.selectPage(page, null);
}

关键特性说明

  1. 自动生成SQL:无需编写XML文件,基础CRUD自动实现
  2. 主键策略:支持AUTO(数据库自增)、ASSIGN_ID(雪花算法)、UUID
  3. 条件构造器:通过QueryWrapper构建复杂查询条件
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.like("username", "张").lt("age", 30);
    userMapper.selectList(wrapper);
    

常见问题排查

  1. 启动时报错找不到Mapper

    • 确保启动类添加@MapperScan("com.example.mapper")
    • 检查Mapper接口是否标注@Mapper注解
  2. 字段映射失败

    • 检查数据库字段名是否符合驼峰转下划线规则
    • 使用@TableField(value = "db_column")指定字段映射
  3. 分页失效

    • 确认已添加分页插件配置
    • 查询方法参数必须为Page对象

扩展建议

  • 使用代码生成器快速生成Entity/Mapper/Service代码
  • 结合LambdaQueryWrapper实现类型安全的查询条件
  • 通过@Version实现乐观锁功能

版权声明:

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

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