tkmapperr,整合springboot报空指针

如漩涡 发布于 05/28 14:13
阅读 147
收藏 0

不知道是不是tkmapper的问题还是自己的配置有问题,每一个项目不管在什么环境下,第一次请求接口总是会报空指针异常,第二次请求又正常,并且使用postmain等工具请求是不会有这种问题,一旦前后端分离,前端使用ajax请求第一次后台都会报空指针异常,第二次请求又好的,摸不清头脑,请大家帮忙查看一下。

这是我的配置:

@Configuration
@Component
public class DbDruidConfig {
    private Logger logger = LoggerFactory.getLogger(DbDruidConfig.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.removeAbandonedTimeoutMillis}")
    private int removeAbandonedTimeoutMillis;

    @Value("${spring.datasource.removeAbandoned}")
    private boolean removeAbandoned;

    @Value("${spring.datasource.logDifferentThread}")
    private boolean logDifferentThread;

    @Value("${spring.datasource.connectionProperties}")
    private String connectionProperties;

    @Value("${spring.datasource.useGlobalDataSourceStat}")
    private boolean useGlobalDataSourceStat;

    @Value("${spring.datasource.druidRegistrationUrl}")
    private String druidRegistrationUrl;

    @Value("${spring.datasource.resetEnable}")
    private String resetEnable;

    @Value("${spring.datasource.loginUsername}")
    private String loginUsername;

    @Value("${spring.datasource.loginPassword}")
    private String loginPassword;

    @Value("${spring.datasource.filtersUrlPatterns}")
    private String filtersUrlPatterns;

    @Value("${spring.datasource.exclusions}")
    private String exclusions;

    @Value("${spring.datasource.sessionStatMaxCount}")
    private String sessionStatMaxCount;

    @Value("${spring.datasource.sessionStatEnable}")
    private String sessionStatEnable;

    @Value("${spring.datasource.principalSessionName}")
    private String principalSessionName;

    @Value("${spring.datasource.profileEnable}")
    private String profileEnable;

    @Value("${spring.datasource.filters:stat,wall,log4j}")
    private String filters;


    @Bean(initMethod = "init", destroyMethod = "close")
    @Primary
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(dbUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxActive(maxActive);
        dataSource.setMaxWait(maxWait);
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestOnReturn(testOnReturn);
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        dataSource.setRemoveAbandonedTimeoutMillis(removeAbandonedTimeoutMillis);
        dataSource.setRemoveAbandoned(removeAbandoned);
        dataSource.setLogDifferentThread(logDifferentThread);
        //设置datasource
        try {
            dataSource.setFilters(filters);
        }
        catch(SQLException e) {
            e.printStackTrace();
            logger.error("Druid URL过滤设置失败", e);
        }
        dataSource.setConnectionProperties(connectionProperties);
        dataSource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
        return dataSource;
    }

    @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setTypeAliasesPackage("com.yc.**.domain");
        //设置mybatis configuration 扫描路径
        sqlSessionFactoryBean.setConfiguration(mybatisConfig());
        /*设置为空照常返回对象*/
//        Configuration configuration= new Configuration();
//        configuration.setCallSettersOnNulls(true);
//        sqlSessionFactoryBean.setConfiguration(configuration);
        //分页插件设置
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        // 分页尺寸为0时查询所有纪录不再执行分页
        properties.setProperty("pageSizeZero", "true");
        // 页码<=0 查询第一页,页码>=总页数查询最后一页
        properties.setProperty("reasonable", "true");
        // 支持通过 Mapper 接口参数来传递分页参数
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        //添加分页插件
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
        //添加mapper 扫描路径
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mybatis/mapper/*.xml"));
        sqlSessionFactoryBean.setDataSource(dataSource());
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 配置 Druid 监控页面。Druid 提供了数据库链接状态和 SQL 执行的页面,
     * 方便开发者查看自己的程序的数据库连接与操作状态,这个监控后台的页面 Servlet 是 StatViewServlet,
     * 我们配置好他,就能打开监控后台查看数据了:项目URL/配置的Druid监控后台路径(就是上面druidRegistrationUrl变量) 来访问到 Druid 的监控后台
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletBean = new ServletRegistrationBean(new StatViewServlet(), druidRegistrationUrl);
        servletBean.addInitParameter("resetEnable", resetEnable);
        servletBean.addInitParameter("loginUsername", loginUsername);
        servletBean.addInitParameter("loginPassword", loginPassword);
        return servletBean;
    }

    /**
     * 给监控后台加上一些过滤,避免一些没必要的资源和页面被统计进去,配置一个 WebStatFilter
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistration() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns(filtersUrlPatterns);
        filterRegistrationBean.addInitParameter("exclusions", exclusions);
        filterRegistrationBean.addInitParameter("sessionStatMaxCount", sessionStatMaxCount);
        filterRegistrationBean.addInitParameter("sessionStatEnable", sessionStatEnable);
        filterRegistrationBean.addInitParameter("principalSessionName", principalSessionName);
        filterRegistrationBean.addInitParameter("profileEnable", profileEnable);
        return filterRegistrationBean;
    }

    /**
     * 与mybatis-config.xml对应的 java类,通过java对象({@link org.apache.ibatis.session.Configuration})来设置,删掉xml配置文件
     * typeAliases的配置可以参考{@link  org.apache.ibatis.session.Configuration#getTypeAliasRegistry()} ,一般常用的对象都已经默认配置
     *
     * @return
     */
    private org.apache.ibatis.session.Configuration mybatisConfig() {
        org.apache.ibatis.session.Configuration mybatisConfig = new org.apache.ibatis.session.Configuration();
        //默认情况下,Mybatis对Map的解析生成, 如果值(value)为null的话,那么key也不会被加入到map中,因此需要设置callSettersOnNulls为true
        mybatisConfig.setCallSettersOnNulls(true);
        return mybatisConfig;
    }
}
@Configuration
@AutoConfigureAfter(DbDruidConfig.class)
public class MybatisConfig {


    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.yc.*.mapper");

        // 配置通用Mapper,详情请查阅官方文档
        Properties properties = new Properties();
        properties.setProperty("mappers", "com.yc.oralhospital.core.Mapper");
        // insert、update是否判断字符串类型!='' 即 test="str != null"表达式内是否追加 and str != ''
        properties.setProperty("notEmpty", "false");
        properties.setProperty("IDENTITY", "SELECT REPLACE(UUID(),\"-\",\"\")");
        properties.setProperty("ORDER","BEFORE");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }


}
###### 数据库配置 ########
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://47.106.137.133:3306/yckq?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=yckq-root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.removeAbandonedTimeoutMillis=20000
spring.datasource.removeAbandoned=true
spring.datasource.logDifferentThread=true
# Druid 监控 Servlet 配置参数
spring.datasource.druidRegistrationUrl=/druid/*
spring.datasource.resetEnable=true
spring.datasource.loginUsername=admin
spring.datasource.loginPassword=123456
# Druid 监控过滤相关配置参数
spring.datasource.filtersUrlPatterns=/*
spring.datasource.exclusions='*.js,*.gif,*.jpg,*.jpeg,*.png,*.css,*.ico,*.jsp,/druid/*'
spring.datasource.sessionStatMaxCount=2000
spring.datasource.sessionStatEnable=true
spring.datasource.principalSessionName=session_user_key
spring.datasource.profileEnable=true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
spring.datasource.useGlobalDataSourceStat=true
       <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.6</version>
        </dependency>

以上就是我的pom文件依赖以及配置文件内容还有我的配置类,下面是控制台报错内容,第一次ajax请求都会报的错,第二次不会

加载中
0
z
zdp06623

MapperScannerConfigurer要用tk.mybatis.spring.mapper下的

如漩涡
如漩涡
import tk.mybatis.spring.mapper.MapperScannerConfigurer; 是这个下面的
返回顶部
顶部