-
在pom文件中导入maven坐标
1.XML<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.23</version> </dependency>
-
创建maven项目的目录结构
-
创建ResultBean作为返回包装类
1.javapackage com.app.user.common; import lombok.Data; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * 返回bean信息 * * @author Administrator */ @Data public class ResultBean<T> implements Serializable { private static final long serialVersionUID = -6759928086797729382L; /** * 编码:1成功,0和其它数字为失败 */ private Integer code; /** * 错误信息 */ private String msg; /** * 数据 */ private T data; /** * 动态数据 */ private Map map = new HashMap(); public static <T> ResultBean<T> success(T object) { ResultBean<T> r = new ResultBean<T>(); r.data = object; r.code = 1; return r; } public static <T> ResultBean<T> error(String msg) { ResultBean r = new ResultBean(); r.msg = msg; r.code = 0; return r; } public ResultBean<T> add(String key, Object value) { this.map.put(key, value); return this; } }
-
创建mybatis plus的分页配置信息
1.javapackage com.app.user.config; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 配置MybatisPlus的配置信息 * * @author Administrator */ @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { // 获取MybatisPlus的拦截器链 MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); // 添加分页拦截器PaginationInnerInterceptor,实现自动分页 mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); return mybatisPlusInterceptor; } }
-
创建表实体类信息
1.javapackage com.app.user.pojo; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; /** * 用户实体类 * * @author Administrator */ @Data @TableName(value = "tb_user") public class User { /** * 主键 */ private Long id; /** * 用户名 */ private String username; /** * 联系电话 */ private String phone; }
-
创建mapper类
1.javapackage com.app.user.mapper; import com.app.user.pojo.User; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 用户mapper * * @author Administrator */ @Mapper public interface UserMapper extends BaseMapper<User> { /** * 计算数目 * * @return 返回计算数目 */ int countNum(); }
-
创建服务接口类
1.javapackage com.app.user.service; import com.app.user.pojo.User; import com.baomidou.mybatisplus.extension.service.IService; /** * 用户服务接口 * * @author Administrator */ public interface UserService extends IService<User> { /** * 计算数目 * * @return 返回记录数 */ int countNum(); }
-
创建服务接口类实现类
1.javapackage com.app.user.service.impl; import com.app.user.mapper.UserMapper; import com.app.user.pojo.User; import com.app.user.service.UserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * 用户服务 * * @author Administrator */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public int countNum() { // 使用原生的xml文件mapper查询表记录 return this.baseMapper.countNum(); } }
-
创建服务的controller类
1.javapackage com.app.user.controller; import cn.hutool.core.util.StrUtil; import com.app.user.common.ResultBean; import com.app.user.pojo.User; import com.app.user.service.UserService; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * 用户控制器 * * @author Administrator */ @RestController @RequestMapping("/users") @Slf4j @RequiredArgsConstructor public class UserController { /** * 结合@RequiredArgsConstructor进行构造器注入 */ private final UserService userService; /** * 新增用户 * * @param user 用户信息 * @return 用户信息 */ @PostMapping public ResultBean<User> save(@RequestBody User user) { log.info("新增用户,用户信息:{}", user.toString()); userService.save(user); return ResultBean.success(user); } /** * 根据id修改用户信息 * * @param user 用户信息 * @return 修改提示信息 */ @PutMapping public ResultBean<String> update(HttpServletRequest request, @RequestBody User user) { log.info(user.toString()); userService.updateById(user); return ResultBean.success("用户信息修改成功"); } /** * 根据id查询用户信息 * * @param id 用户id * @return 用户信息 */ @GetMapping("/{id}") public ResultBean<User> getById(@PathVariable Long id) { log.info("根据id查询用户信息..."); User user = userService.getById(id); if (user != null) { return ResultBean.success(user); } return ResultBean.error("没有查询到对应用户信息"); } /** * 用户信息分页 * * @param page 当前页 * @param pageSize 每页显示条数 * @param username 用户名 * @return 返回分页用户信息 */ @GetMapping("/page") public ResultBean<Page<User>> page(int page, int pageSize, String username) { log.info("page = {},pageSize = {},username = {}", page, pageSize, username); // 1、构造简单分页模型 Page<User> pageInfo = new Page<>(page, pageSize); // 2、构造条件构造器 LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); // 3、添加用户名过滤条件,使用模糊匹配,不为空时才生效 queryWrapper.like(StrUtil.isNotEmpty(username), User::getUsername, username); // 4、添加排序条件 queryWrapper.orderByDesc(User::getId); // 5、执行查询,查询的结果将会直接存在于pageInfo对象中 userService.page(pageInfo, queryWrapper); return ResultBean.success(pageInfo); } /** * 获取用户记录数 * * @return 返回记录数 */ @GetMapping("/count") public ResultBean<Integer> count() { log.info("计算用户数目..."); int i = userService.countNum(); return ResultBean.success(i); } }
-
在resources的文件夹创建mapper文件夹,并创建mapper.xml文件,示例创建的是UserMapper.xml文件
1.XML<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.app.user.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.app.user.pojo.User"> <result property="id" column="id" jdbcType="DECIMAL"/> <result property="username" column="username" jdbcType="VARCHAR"/> <result property="phone" column="phone" jdbcType="VARCHAR"/> </resultMap> <sql id="Base_Column_List"> id,username,phone </sql> <select id="countNum" resultType="int"> select count(*) from tb_user; </select> </mapper>
-
创建application.yml文件并配置下列信息
1.XMLserver: port: 8080 spring: application: #应用的名称,可选 name: user-service datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3333/user_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource mybatis-plus: configuration: #在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射 map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: db-config: id-type: ASSIGN_ID mapper-locations: classpath:mapper/*.xml
-
创建logback.xml日志文件并配置下列信息
1.XML<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Licensed to the Apache Software Foundation (ASF) under one or more ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ The ASF licenses this file to You under the Apache License, Version 2.0 ~ (the "License"); you may not use this file except in compliance with ~ the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <configuration> <property name="log.context.name" value="sharding-jdbc-spring-namespace-mybatis-example" /> <property name="log.charset" value="UTF-8" /> <property name="log.pattern" value="[%-5level] %date --%thread-- [%logger] %msg %n" /> <contextName>${log.context.name}</contextName> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder charset="${log.charset}"> <pattern>${log.pattern}</pattern> </encoder> </appender> <root> <level value="info" /> <appender-ref ref="STDOUT" /> </root> </configuration>
-
直接启动SpringBootApplication启动类即可
【Spring Boot】如何集成mybatis-plus
upton-nan2023-12-11 16:40
相关推荐
激流丶14 分钟前
【Kafka 实战】如何解决Kafka Topic数量过多带来的性能问题?Themberfue18 分钟前
Java多线程详解⑤(全程干货!!!)线程安全问题 || 锁 || synchronized让学习成为一种生活方式35 分钟前
R包下载太慢安装中止的解决策略-R语言003晨曦_子画40 分钟前
编程语言之战:AI 之后的 Kotlin 与 Java南宫生1 小时前
贪心算法习题其三【力扣】【算法学习day.20】Heavydrink1 小时前
HTTP动词与状态码ktkiko111 小时前
Java中的远程方法调用——RPC详解计算机-秋大田2 小时前
基于Spring Boot的船舶监造系统的设计与实现,LW+源码+讲解神里大人2 小时前
idea、pycharm等软件的文件名红色怎么变绿色沐雪架构师2 小时前
mybatis连接PGSQL中对于json和jsonb的处理