qq_45027542 2021-08-13 18:43 采纳率: 100%
浏览 419
已结题

Mybatis中使用工具类获取SqlSession报空指针异常

错误一开始也是同样空指针,然后报错链接过去的却是其他项目的工具类,后面把其他项目给删掉了,但还是报错空指针,这回链接的就是本项目的了,但问题是测试类运行了前三个方法的时候是没有问题的,但到了第四个方法就报错了,不知道是中途休息的时候点到了哪里还是怎么样,接着同类下其他的测试方法也开始报同样的错误。

结构

img

配置环境

<?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>
    <!-- 1 配置环境,默认的环境id为mysql -->
    <environments default="mysql">
        <!-- 1.2 配置id,为mysql的数据库环境 -->
        <environment id="mysql">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>    
    </environments>
    <!-- 2 配置Mapper的位置 -->
    <mappers>
        <!-- 可以配置多个Mapper -->
        <mapper resource="com/itheima/mapper/CustomerMapper.xml" />
    </mappers>
</configuration>

映射文件

<?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">
<!-- namespace表示命名空间 -->
<mapper namespace="com.itheima.mapper.CustomerMapper">
    <!-- <if>元素的使用 -->
    <select id="findCustomerByNameAndJobs"
        parameterType="com.itheima.po.Customer"
        resultType="com.itheima.po.Customer">
        select * from t_customer
        <where>
            <if test="username != null and username != '' ">
                and username like concat('%',#{username},'%')
            </if>
            <if test="jobs != null and jobs != '' ">
                and jobs = #{jobs}
            </if>
        </where>
    </select>

    <!-- <choose>(<when>,<otherwise>)元素使用 -->
    <select id="findCustomerByNameOrJobs"
        parameterType="com.itheima.po.Customer"
        resultType="com.itheima.po.Customer">
        select * from t_customer
        <trim prefix="where" prefixOverrides="and">
            <choose>
                <when test="username != null and username != '' ">
                    and username like concat('%',#{username},'%')
                </when>
                <when test="jobs != null and jobs != '' ">
                    and jobs = #{jobs}
                </when>
                <otherwise>
                    and phone is null
                </otherwise>
            </choose>
        </trim>
    </select>

    <!-- <set>元素 -->
    <update id="updateCustomer" parameterType="c">
        update t_customer
        <set>    <!-- <set>元素会去掉多余的逗号 -->
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="jobs != null and jobs != ''">
                jobs = #{jobs},
            </if>
            <if test="phone != null and phone != ''">
                phone = #{phone},
            </if>
        </set>
        where id = #{id}
    </update>

    <!-- <foreach>元素使用 -->
    <select id="findCustomerByIds" parameterType="List"
        resultType="com.itheima.po.Customer">
        select * from t_customer where id in
        <foreach item="id" index="index" collection="list" open="("
            separator="," close=")">
            #{id}
        </foreach>
    </select>
</mapper>


测试类

package com.itheima.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.itheima.po.Customer;
import com.itheima.utils.MybatisUtils;


/**
 * 入门程序测试类
 */
public class MybatisTest {
    /**
     * 根据客户姓名和职业组合条件查询客户信息列表
     */
    @Test
    public void findCustomerByNameAndJobsTest() {
        //通过工具类生成SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSession();
        //创建Customer对象,封装需要组合查询的条件
        Customer customer = new Customer();
        customer.setUsername("jack");
        customer.setJobs("teacher");
        //执行SqlSession的查询方法,返回结果集
        List<Customer> customers = sqlSession.selectList("com.itheima.mapper.CustomerMapper.findCustomerByNameAndJobs", customer);
        //输出查询结果
        for(Customer cust : customers) {
            //打印输出结果
            System.out.println(cust);
        }
        //关闭SqlSession
        sqlSession.close();
    }
    
    @Test
    public void findCustomerByNameOrJobsTest() {
        SqlSession sqlSession = MybatisUtils.getSession();
        Customer customer = new Customer();
        customer.setUsername("jack");
        customer.setJobs("teacher");
        
        List<Customer> customers = sqlSession.selectList("com.itheima.mapper.CustomerMapper.findCustomerByNameOrJobs", customer);
        for(Customer customers2 : customers) {
            System.out.println(customers2);
        }    
        sqlSession.close();
    }
    
    /**
     * 更新客户信息
     */
    @Test
    public void updateCustomerTest() {
        SqlSession sqlSession = MybatisUtils.getSession();
        Customer customer = new Customer();
        customer.setId(4);
        customer.setJobs("waiter");
        customer.setPhone("17777777777");
        int rows = sqlSession.update("com.itheima.mapper.CustomerMapper.updateCustomer", customer);
        if(rows>0) {
            System.out.println("成功更新了" +rows+ "条语句!");
        }else {
            System.out.println("更新失败!");
        }
        //提交事务
        sqlSession.commit();
        //关闭SqlSession
        sqlSession.close();
    }
    
    /**
     * 根据客户编号批量查询客户信息
     */
    @Test
    public void findCustomerByIdsTest() {
        //获取SqlSession
        SqlSession sqlSession = MybatisUtils.getSession();    
        //创建List集合,封装查询id
        List<Integer> ids = new ArrayList<>();
        for(int i=0; i>3; i++) {
            ids.add(i);
        }
        //执行SqlSession的查询方法,返回结果集
        List<Customer> customers = sqlSession.selectList("com.itheima.mapper.CustomerMapper.findCustomerByIds", ids);
        //输出查询结果信息
        for(Customer customer : customers) {
            //打印输出结果
            System.out.println(customer);
        }
        //关闭SqlSession
        sqlSession.close();
    }
}

工具类

package com.itheima.utils;

import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {
    
    private static SqlSessionFactory sqlSessionFactory = null;
    
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}
  • 写回答

2条回答 默认 最新

  • CSDN专家-sinJack 2021-08-13 18:49
    关注

    空指针异常的日志记录发出来看下,你根据日志记录看下哪里报错就知道了,都会提示哪个类,方法,行数等。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 8月21日
  • 已采纳回答 8月13日
  • 修改了问题 8月13日
  • 创建了问题 8月13日

悬赏问题

  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真