springboot+mp,测试的时候遇到空指针异常

img

从程序上面分析,能报错空指针的也只有BookMapper.insert(book);这一行了,至于为什么报了空指针异常,你在测试类看不出来的,最根本原因还是去你的bookMapper里面去找,最终定位到了xml文件,90%是你的映射写错了,仔细检查一下,比如说
1.xml里的sql语句在最后都没有分号,而你却加了分号
2.没有准确的映射到你的实体类
3.如果你的添加的sql是insert into xx values(#{id},#{name},#{author},#{age}),你要注意啦,values里的字段顺序要和你的实体类创建对象的属性顺序一致才可以,否则就是添加失败
values()里的字段顺序就是你建表时字段的排序,实体类创建对象时,属性的排序必须一一对应,例如
Book book=new Book(id,name,author,age);

bookMapper这个对象没注入成功 为null 输出bookMapper你就能看见。

配置里面也写映射路径和别名了

spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jabc:mysql://localhost:3306/library?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root

mybatis-plus:
mapper-locations: classpath:mapper/*.xml
typeAliasesPackage: com.example.entity


package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.Book;

public interface BookMapper extends BaseMapper {

}


package com.example.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
/*
* 分页插件,自动识别数据库类型
*/
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}


package com.example.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class Book implements Serializable {

private Integer id;
private String name;
private String author;

}