java druid mybatis 配置及遇到的问题解决

文章目录


java学习记录

我的springboot时3.2.4

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
   # druid配置 

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#配置druid
spring.datasource.druid.url=jdbc:sqlserver://localhost;databaseName=data;encrypt=false;trustServerCertificate=false;loginTimeout=60;sslProtocol=TLSv1
spring.datasource.druid.username=sa
spring.datasource.druid.password=sa
spring.datasource.druid.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver


#配置监控访问页面信息

spring.datasource.druid.stat-view-servlet.enabled=true

spring.datasource.druid.stat-view-servlet.login-password=admin

spring.datasource.druid.stat-view-servlet.login-username=admin

spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*

#用于验证连接的SQL查询语句 必须配置 否则会报错 validation fail
spring.datasource.druid.validation-query=SELECT 1
#表示连接在池中最小的空闲时间
spring.datasource.druid.min-evictable-idle-time-millis= 300000
#连接在空闲时是否执行验证查询
spring.datasource.druid.test-while-idle= true
# 借出时是否执行验证查询
spring.datasource.druid.test-on-borrow=true
# 归还时是否执行验证查询。
spring.datasource.druid.test-on-return=false
#用来设置是否对预编译的SQL语句进行池化。当设置为 true 时,
# Druid会缓存预编译的语句,以提高重复执行相同类型的SQL语句的性能。
# 这可以降低预编译语句创建和销毁的开销,并且在一定程度上可以提高数据库的性能。
spring.datasource.druid.pool-prepared-statements=true
#这个属性用来设置每个连接最大预编译语句池的大小。
# 如果 pool-prepared-statements 被设置为 true,
# 那么每个连接都会维护一个预编译语句池,
# 最多缓存此数量的预编译语句。这可以控制每个连接上预编译语句的数量,避免无限制地缓存大量预编译语句
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#中,spring.datasource.druid.stat-view-servlet.allow
# 用于设置允许访问Druid监控页面的IP地址,通常用于限制监控页面的访问权限。
#spring.datasource.druid.stat-view-servlet.allow=192.168.99.116
#Druid监控页面的访问路径

#禁用了监控统计页面上的“Reset”功能,
spring.datasource.druid.stat-view-servlet.reset-enable=true
#web 监控
#启用 Druid 的 Web 状态过滤器,用于监控统计信息
spring.datasource.druid.web-stat-filter.enabled=true
#配置 Web 状态过滤器拦截的 URL 地址模式。它会拦截所有的 URL 地址。
spring.datasource.druid.web-stat-filter.url-pattern=/*
#配置排除的 URL 地址模式,这些 URL 地址的请求不会被拦截和统计。常见的静态资源和 Druid 监控页面的 URL 地址。
spring.datasource.druid.web-stat-filter.exclusions='*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
#连接池的初始化连接数。
spring.datasource.druid.initial-size= 5
#连接池的最小空闲连接数。
spring.datasource.druid.min-idle= 5
#连接池的最大活跃连接数。
spring.datasource.druid.max-active= 20
#连接池的初始化将以异步方式进行
spring.datasource.druid.async-init=true
#设置了登录超时时间为 6000 秒,即 100 分钟。
spring.datasource.druid.login-timeout=600
#开启慢 SQL 执行日志记录功能,可以将执行时间超过阈值的 SQL 语句信息记录下来
spring.datasource.druid.filter.stat.log-slow-sql=true
#设置慢 SQL 的阈值,单位为毫秒。这里设置为 1000 毫秒,表示超过 1 秒的 SQL 执行时间将被记录下来。
spring.datasource.druid.filter.stat.slow-sql-millis=1000
#启用 Druid 的 Stat 过滤器,用于收集监控数据,包括 SQL 的执行情况、连接池状态等。
spring.datasource.druid.filter.stat.enabled=true
#启用 Druid 的 Wall 防火墙功能,用于防止 SQL 注入攻击。
spring.datasource.druid.filter.wall.enabled=true
#配置 Wall 防火墙是否允许执行删除表的操作。如果设置为 false,将禁止执行删除表的操作。
spring.datasource.druid.filter.wall.config.drop-table-allow=false


##监控SpringBean
spring.datasource.druid.aop-patterns=org.wang.reggie.*
##底层开启功能  wall防火墙  stat sql监控
spring.datasource.druid.filters=stat,wall


#日志配置
logging.charset.console=utf-8
logging.config= classpath:static/log4j2.xml
##设置日志级别
logging.level.org.apache.catalina=info
logging.level.org.apache.commons.beanutils.converters=info
logging.level.org.apache.coyote.http11.Http11Processor=info
logging.level.org.apache.http=info
logging.level.org.apache.tomcat=info
logging.level.org.springframework=info
logging.level.com.chinamobile.cmss.bdpaas.resource.monitor=debug



#mybatis配置

#配置为false则不会RolID转换为 Role_I_D
mybatis-plus.configuration.map-underscore-to-camel-case=false
#表示在从 ResultSet 映射数据到实体对象时,
# 如果数据库中的字段值为 NULL,则不会调用实体类的 setter 方法进行赋值;'
# 如果该项被设置为 true,则会调用 setter 方法进行赋值。
mybatis-plus.configuration.call-setters-on-nulls=true
#### 日志输出到控制台
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

我配置完成以后 访问http://192.168.99.116:9090/api/druid/login.html一直报错404,
然后我再MyBatisDruidConfig 中配置了 druidStatViewServlet也不好用,
最后发现时springboot版本与druid不兼容
原来引入的

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.18</version>
        </dependency>

然后最后升级成1.2.22才成功

途中还遇到了StatViewServlet 导入类失败的问题,然后把druid依赖升级1.2.22就好了,然后引入

import com.alibaba.druid.support.jakarta.StatViewServlet;
import com.alibaba.druid.support.jakarta.WebStatFilter;
才可以

最后附上config配置代码

package com.gas;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.jakarta.StatViewServlet;
import com.alibaba.druid.support.jakarta.WebStatFilter;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author admin
 */
@Configuration
@MapperScan(basePackages="com.gas.Mappers")
public class MyBatisDruidConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource dataSource() {
        return new DruidDataSource();
    }
    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean ();
        factory.setDataSource(dataSource());
    // 设置MyBatis Plus的配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(false);
        configuration.setCallSettersOnNulls(true);
        // 其他MyBatis Plus的配置设置

        factory.setConfiguration(configuration);


        // factory.setTypeAliasesPackage("com.gas.Models");
        return factory;
    }

    /**
     * StatViewServlet com.alibaba.druid.support.jakarta
     * @return
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> druidStatViewServlet() {
        ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        // 添加初始化参数,也就是允许访问的用户名和密码
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        WebStatFilter webStatFilter = new WebStatFilter();

        filterRegistrationBean.setFilter(webStatFilter);
        filterRegistrationBean.addUrlPatterns("/*");

        // 添加不需要忽略的格式信息
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

        // 添加需要监控的URL
        filterRegistrationBean.addInitParameter("profileEnable", "true");

        return filterRegistrationBean;
    }
    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor(){
        //新建MybatisPlus拦截器
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //新建分页拦截器paginationInnerInterceptor
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        //设置分页拦截器的一些属性
        paginationInnerInterceptor.setOverflow(true);
        paginationInnerInterceptor.setMaxLimit(100L);
        //把分页拦截器添加到MybatisPlus拦截器中
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        //添加组件,大功告成!
        return mybatisPlusInterceptor;
    }
}

最后终于访问成功
在这里插入图片描述
登录自己配置的用户名密码 ,我写的分别时admin,admin
成功

然后新建UserInfoMapper 继承BaseMapper
@Mapper
public interface UsersInfoMapper extends BaseMapper {

}
此处的@Mapper可以不写,但是要在启动类配置 //@MapperScan(basePackages = “com.gas.Mappers”)
如果在启动类配置了//@MapperScan(basePackages = “com.gas.Mappers”) 那么@Mapper就可以不写

然后在controller中依赖注入 mapper

 SQLServerHelper helper;
    PublicBLL bll;


    DataSource source;
    //此处直接使用了mapper ,如果需要一定的业务逻辑,可以新建UserInfoService 基础mapper然后重新实现对应的方法
    UsersInfoMapper mapper;

    // 依赖注入
    @Autowired
    public PublicController(SQLServerHelper helper, PublicBLL bll, DataSource source, UsersInfoMapper mapper) {
        this.helper = helper;
        this.bll = bll;
        this.source = source;
        this.mapper = mapper;
    }

最后在在自己的方法内使用mapper就可以了
下面是个简单的例子

	@GetMapping("/getUsers")
    public BusinessResponse<?> getUsers(String name) throws SQLException {
        //确认是否使用了Druid
        System.out.println("当前数据源:{}" + source.getClass().getName());

        // LambdaQueryWrapper可以使用表对应的实体类直接调用get方法获取列名,而QueryWrapper只能填列名字符串,
        //LambdaQueryWrapper<UsersInfoEntity> lqw = new LambdaQueryWrapper<>();

        //lqw.eq(UsersInfoEntity::getOptUserId, 72);
        List<UsersInfoEntity> list = new ArrayList<>();

        //
        try {
            list = mapper.selectList(null);
        } catch (Exception e) {
            return BusinessResponse.fail("01", e.getMessage());
        }

        //
        // List<UsersInfoEntity> sList=userService.getBaseMapper().selectList(lqw);
        //
        // //创建分页   1  当前页码 2 每页数量
        // Page<UsersInfoEntity>userPage=new Page<>(1,2);
        // //获取分页记录
        // Page<UsersInfoEntity> result = userService.page(userPage);
        //

       /*
       * eq 就是 equal等于
        ne就是 not equal不等于
        gt 就是 greater than大于
        lt 就是 less than小于
        ge 就是 greater than or equal 大于等于
        le 就是 less than or equal 小于等于
        in 就是 in 包含(数组)
        isNull 就是 等于null
        between 就是 在2个条件之间(包括边界值)
        like就是 模糊查询
       * */
        // QueryWrapper<UsersInfoEntity> qw=new QueryWrapper<>();
        // qw.eq("optUserId","75");
        // List<UsersInfoEntity> usersInfoEntities = userService.getBaseMapper().selectList(qw);

        return BusinessResponse.success(list);
    }

我的实体类:

package com.gas.Entitys;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

/**
 * @author admin
 */
@Data
//如果关键字冲突了,因为需要额外再加一个单引号 eg:("`order`")
@TableName("Sys_Users")
public class UsersInfoEntity {

    @TableId(type=IdType.AUTO)
    public  Integer optUserId ;

    public  String loginName;

    public  String password;
    public  String realName;
    public  String roleId;
    public  String empId;
    // 使用注解来配置 CreateDate 字段
    @TableField(value = "CreateDate", fill = FieldFill.INSERT)
    public  String createDate;
}

实体类遇到了问题,我数据库时optUserId,然后打印的查询语句变成了opt_user_id
原因时配置没有生效 可以在MyBatisDruidConfig 中加载mybatisplus的配置

       // 设置MyBatis Plus的配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(false);
        configuration.setCallSettersOnNulls(true);
        // 其他MyBatis Plus的配置设置

        factory.setConfiguration(configuration);

然后就解决了问题
最终的apipost中请求
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卢小亦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值