Mybatis配置sqlsession 空指针异常 全解析

报错

nested exception is java.lang.NullPointerException 空指针异常

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-11-18 16:44:55.380 ERROR 2056 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl' defined in file [W:\~IDEA\web_class\back_end\target\classes\com\example\web_class\service\impl\UserServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.web_class.service.impl.UserServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException

Error building SqlSession.

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.web_class.service.impl.UserServiceImpl]: Constructor threw exception; nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in mapper/UserMapper.xml

错误原因及解决方案

过程分析(排错的过程、思路)
项目结构:
在这里插入图片描述

错误原因:忘记加注解,或者注解加错了

  1. UserController调用userMapper接口
package com.example.web_class.controller; 
......
@Autowired   /****** 1.  @Autowired 忘记加会出现报错!******/
private UserService userService;
    
@PostMapping("login")
    public Result login(
            @RequestParam(value = "username",required = false) String username,
            @RequestParam(value = "password",required = false) String password,
            ModelAndView modelAndView){
        User user = User.builder().username(username).password(password).build();
        //userService被调用
        String data = userService.login(user);
        return data!=null? ResultGenerator.genSuccessResult(data):ResultGenerator.genFailResult("账号密码错误!");
    };
  1. 查看userService接口
package com.example.web_class.service;
......
@Service  /****** 2.  @Service  忘记加会出现报错!******/
public interface UserService {
    String login(User user);
}
  1. userService接口的实现 implement
package com.example.web_class.service.impl;
......
@Service  /****** 3.  @Service  忘记加会出现报错!******/
public class UserServiceImpl implements UserService{
    String resource= "config/mybatis-config.xml";
    //    JAVA中getResourceAsStream这个方法是用来获取配置文件
    InputStream inputStream= Resources.class.getResourceAsStream((resource));
    /******** 接下来这几句就是报出空指针异常的语句!!!  **********/
    InputStream inputStream= Resources.class.getResourceAsStream((resource));
    SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession=sqlSessionFactory.openSession(true);
    UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
    ......
}

配置文件的路径写错了

String resource= "config/mybatis-config.xml";
IDEA 无法识别java包下面的xml文件。可以修改pom文件识别。

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

配置文件里面mapper.xml的路径写错了

//mybatis-config.xml
......
    <mappers>
<!--        <mapper resource="com/example/web_class/mapper/UserMapper.xml"/>-->
        <mapper resource="mapper/UserMapper.xml"/>
        <mapper resource="mapper/MailMapper.xml"/>
    </mappers>
......

A 无法识别java包下面的xml文件,同样可以修改pom文件识别。xml路径中不能时com.example.这样的,要用/,同时注意url、resource等的区别。

超级难以难以察觉到的错误!导入错误的包!(resources)

在这里插入图片描述

import org.apache.ibatis.io.Resources;
...
//正确的resources包应该是 org.apache.ibatis.io.Resources;
    InputStream inputStream= Resources.getResourceAsStream((resource));
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis使用SqlSession来执行数据库操作。SqlSessionMyBatis中的核心接口,它提供了多种方法来执行SQL语句、提交事务、获取映射器等操作。 首先,你需要通过SqlSessionFactory来创建SqlSession对象。SqlSessionFactory是由MyBatis配置文件和映射文件构建而成的,它负责创建SqlSession对象。 下面是使用SqlSessionFactory创建SqlSession的代码示例: ```java String resource = "mybatis-config.xml"; // MyBatis配置文件的路径 InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); ``` 一旦你获得了SqlSession对象,你就可以使用它来执行各种数据库操作。以下是一些常用的SqlSession方法: - `selectOne(String statement, Object parameter)`:查询单条记录。 - `selectList(String statement, Object parameter)`:查询多条记录。 - `insert(String statement, Object parameter)`:插入数据。 - `update(String statement, Object parameter)`:更新数据。 - `delete(String statement, Object parameter)`:删除数据。 - `commit()`:提交事务。 - `rollback()`:回滚事务。 其中,`statement`参数是映射文件中定义的SQL语句的唯一标识,`parameter`参数是传递给SQL语句的参数。 使用完SqlSession后,记得关闭它以释放资源: ```java sqlSession.close(); ``` 这就是MyBatis中使用SqlSession进行数据库操作的基本流程。希望能对你有所帮助!如果还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

caesarding

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

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

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

打赏作者

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

抵扣说明:

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

余额充值