springboot3项目的搭建二(可连数据库的子模块及mybatisplus数据分页配置)

springboot3项目的搭建二(可连数据库的子模块)

 1.先引入pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.qiqi</groupId>
        <artifactId>java_invite</artifactId>
        <version>1.0.0</version>
    </parent>

    <artifactId>invite_auth</artifactId>
    <description>认证模块</description>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <!-- mybatisPlus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>

        <!-- 实体类注解工具 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- 阿里数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>

        <!-- 添加Spring Boot DevTools依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>


        <dependency>
            <groupId>com.qiqi</groupId>
            <artifactId>invite_common</artifactId>
        </dependency>



    </dependencies>

</project>

2. 因为要连接数据库,所以设置mybatis的一套

  2.1 配置application.yml

# Spring配置
spring:
  # 资源信息
  messages:
    # 国际化资源文件路径
    basename: i18n/messages
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  # 多配置文件 application-druid.yml
  profiles:
    active: druid
  # 文件上传
  servlet:
    multipart:
      # 单个文件大小
      max-file-size:  10MB
      # 设置总上传的文件大小
      max-request-size:  20MB
  # 服务模块
  devtools:
    restart:
      # 热部署开关
      enabled: true



# MyBatis Plus配置
mybatis-plus:
  # 加载全局的配置文件
  #config-location: classpath:mybatis/mybatis-config.xml
  # 加载全局的配置文件
  mapper-locations: classpath:mapper/*Mapper.xml
  # 实体扫描,多个package用逗号或者分号分隔
  type-aliases-package: com.qiqi.**.domain   #自己的实体类地址

  configuration: #(因为这里的配置是mybatis原始配置,所以和上面的config-location有其一即可,不然会报冲突)
    # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #开启驼峰命名法
    call-setters-on-nulls: true
    variables:
      # 自定义表前缀 (mapper.xml文件中使用${tablePrefix})
        tablePrefix: t_
  global-config:
    db-config:
      # mybatisplus 自带的查询中会自动加此值
      table-prefix: t_
      id-type: auto


# 日志配置
logging:
  config: classpath:logback-spring.xml
  level:
    com.qiqi: debug
    org.springframework: warn

 

  2.2 数据库的配置application-druid.yml

# 数据源配置
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource  #自定义数据源
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/java_invite?autoReconnect=true&useUnicode=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 #自己的数据库名称
    username: root
    password: root
    druid:
      # 初始连接数
      initialSize: 5
      # 最小连接池数量
      minIdle: 10
      # 最大连接池数量
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置连接超时时间
      connectTimeout: 30000
      # 配置网络超时时间
      socketTimeout: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      # 配置一个连接在池中最大生存的时间,单位是毫秒
      maxEvictableIdleTimeMillis: 900000
      # 配置检测连接是否有效
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      webStatFilter:
        enabled: true
      statViewServlet:
        enabled: true
        # 设置白名单,不填则允许所有访问
        allow:
        url-pattern: /druid/*
        # 控制台管理用户名和密码
        login-username: ruoyi
        login-password: 123456
      filter:
        stat:
          enabled: true
          # 慢SQL记录
          log-slow-sql: true
          slow-sql-millis: 1000
          merge-sql: true
        wall:
          config:
            multi-statement-allow: true

  2.3 mybatis配置的日志  logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 日志存放路径 -->
    <property name="log.path" value="/logs" />
    <!-- 日志输出格式 -->
    <property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />

    <!-- 控制台输出 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
    </appender>

    <!-- 系统日志输出 -->
    <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/sys-info.log</file>
        <!-- 循环政策:基于时间创建日志文件 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 日志文件名格式 -->
            <fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!-- 日志最大的历史 60天 -->
            <maxHistory>60</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!-- 过滤的级别 -->
            <level>INFO</level>
            <!-- 匹配时的操作:接收(记录) -->
            <onMatch>ACCEPT</onMatch>
            <!-- 不匹配时的操作:拒绝(不记录) -->
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/sys-error.log</file>
        <!-- 循环政策:基于时间创建日志文件 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 日志文件名格式 -->
            <fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!-- 日志最大的历史 60天 -->
            <maxHistory>60</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!-- 过滤的级别 -->
            <level>ERROR</level>
            <!-- 匹配时的操作:接收(记录) -->
            <onMatch>ACCEPT</onMatch>
            <!-- 不匹配时的操作:拒绝(不记录) -->
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!-- 用户访问日志输出  -->
    <appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/sys-user.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 按天回滚 daily -->
            <fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!-- 日志最大的历史 60天 -->
            <maxHistory>60</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
    </appender>

    <!-- 系统模块日志级别控制  -->
    <logger name="com.ruoyi" level="info" />
    <!-- Spring日志级别控制  -->
    <logger name="org.springframework" level="warn" />

    <root level="info">
        <appender-ref ref="console" />
    </root>

    <!--系统操作日志-->
    <root level="info">
        <appender-ref ref="file_info" />
        <appender-ref ref="file_error" />
    </root>

    <!--系统用户操作日志-->
    <logger name="sys-user" level="info">
        <appender-ref ref="sys-user"/>
    </logger>
</configuration>

  2.4 如果用 mybatis的xml配置文件 (resources/mybatis/mybatis-config.xml) 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 全局参数 -->
    <settings>
        <!-- 使全局的映射器启用或禁用缓存 -->
        <setting name="cacheEnabled"             value="true"   />
        <!-- 允许JDBC 支持自动生成主键 -->
        <setting name="useGeneratedKeys"         value="true"   />
        <!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
        <setting name="defaultExecutorType"      value="SIMPLE" />
        <!-- 指定 MyBatis 所用日志的具体实现 -->
        <setting name="logImpl"                  value="SLF4J"  />
        <!-- 使用驼峰命名法转换字段 -->
        <setting name="mapUnderscoreToCamelCase" value="true"   />
    </settings>

</configuration>

 

 

3.配置完,按照数据库写实体和mapper接口和mapper.xml 文件

  3.1实体

package com.qiqi.auth.domain.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.time.LocalDateTime;

@Repository
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "admins", keepGlobalPrefix = true)
public class AdminsEntity implements Serializable {

    @TableId(type = IdType.AUTO)
    private Integer id;

    //默认驼峰转换成:user_name,但是数据库字段确是username
    @TableField(value = "username")
    private String userName;

    //字段按照password查
    @TableField(value = "password")
    private String passWord;
    //并且查询操作不显示
    @TableField(value = "cname",select = false)
    private String cName;

    private String email;

    //默认转换规则create_time
    private LocalDateTime createTime;
    private LocalDateTime lastTime;

}

 (表中不存在的字段可以用@TableField(exist = false) 注解修饰)

  3.2 mapper接口

package com.qiqi.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qiqi.auth.domain.entity.AdminsEntity;
import org.apache.ibatis.annotations.Mapper;


@Mapper
public interface AdminsMapper extends BaseMapper<AdminsEntity> {
    AdminsEntity queryOneById();

}

  3.3mapper.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.qiqi.auth.mapper.AdminsMapper">
    <!-- https://www.cnblogs.com/fps2tao/p/17440388.html -->
    <resultMap id="MyAdminMap" type="com.qiqi.auth.domain.entity.AdminsEntity">
        <id property="id" column="admin_id"></id>
        <result property="userName" column="username"></result>
        <result property="passWord" column="password"></result>
        <result property="cName" column="cname"></result>
    </resultMap>

    <!-- https://www.cnblogs.com/fps2tao/p/17439898.html -->
    <select id="queryOneById"  resultMap="MyAdminMap">
        select * from ${tablePrefix}admins where id = 1
    </select>


</mapper>

 

 

项目结构

数据表

 

最后看能不能跑通

 

 

二、分页配置(配置一个拦截器)

package com.qiqi.framework.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig{

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        // 1.创建MybatisPlusInterceptor拦截器
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 2.创建分页拦截器
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setOptimizeJoin(true);
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor = new OptimisticLockerInnerInterceptor();
        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);
        return interceptor;
    }

}

1.然后写一个全查询的mapper.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.qiqi.auth.mapper.AdminsMapper">
    <!-- https://www.cnblogs.com/fps2tao/p/17440388.html -->
    <resultMap id="MyAdminMap" type="com.qiqi.auth.domain.entity.AdminsEntity">
        <id property="id" column="admin_id"></id>
        <result property="userName" column="username"></result>
        <result property="passWord" column="password"></result>
        <result property="cName" column="cname"></result>
    </resultMap>

    <!-- https://www.cnblogs.com/fps2tao/p/17439898.html -->
    <select id="queryOneById"  resultMap="MyAdminMap">
        select * from ${tablePrefix}admins where id = 1
    </select>
    <select id="selectPageEntity"  resultMap="MyAdminMap">
        select * from ${tablePrefix}admins
    </select>


</mapper>

2.控制器测试

    @RequestMapping("/test02")
    @ResponseBody
    public ResultData test02(){

        // 创建分页查询相关参数 page,泛型为 Product,表示查询到的结果对应的实体类为Product
        Page<AdminsEntity> page = new Page<>();
        // 设置分页查询显示第二页的数据,实际开发过程中该参数有前端传递
        page.setCurrent(2);
        // 设置分页查询每页显示四条数据,实际开发过程中该参数有前端传递
        page.setSize(2);

        List<AdminsEntity> adminsList = adminsMapper.selectPageEntity(page);

        return ResultData.success(adminsList); //返回实体
        //return ResultData.error(ReturnCode.EMAIL_EXIST);//返回 邮箱已存在
    }

 

 

 

 

 

 

分页参考 :https://blog.csdn.net/m0_70325779/article/details/137796332

 

posted @ 2024-05-29 22:23  与f  阅读(131)  评论(0编辑  收藏  举报