- 在pom文件中导入maven坐标
-
<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作为返回包装类
-
package 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的分页配置信息
-
package 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 {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {// 获取MybatisPlus的拦截器链MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();// 添加分页拦截器PaginationInnerInterceptor,实现自动分页mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());return mybatisPlusInterceptor;}}
-
- 创建表实体类信息
-
package 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类
-
package 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();}
-
- 创建服务接口类
-
package 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();}
-
- 创建服务接口类实现类
-
package 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 {@Overridepublic int countNum() {// 使用原生的xml文件mapper查询表记录return this.baseMapper.countNum();}}
-
- 创建服务的controller类
-
package 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 用户信息*/@PostMappingpublic ResultBean<User> save(@RequestBody User user) {log.info("新增用户,用户信息:{}", user.toString());userService.save(user);return ResultBean.success(user);}/*** 根据id修改用户信息** @param user 用户信息* @return 修改提示信息*/@PutMappingpublic 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文件
-
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapperPUBLIC "-//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文件并配置下列信息
-
server:port: 8080 spring:application:#应用的名称,可选name: user-servicedatasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3333/user_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: rootpassword: 123456type: com.alibaba.druid.pool.DruidDataSourcemybatis-plus:configuration:#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射map-underscore-to-camel-case: truelog-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:id-type: ASSIGN_IDmapper-locations: classpath:mapper/*.xml
-
- 创建logback.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启动类即可