NoClassDefFoundError: Could not initialize class MyBatisUtils

NoClassDefFoundError: Could not initialize class MyBatisUtils

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.imooc</groupId>
    <artifactId>ImoocMyBatis</artifactId>
    <version>1.0-SNAPSHOT</version>
   <repositories>
        <repository>
            <id>aliyun</id>
            <name>aliyun</name>
            <url>https://maven.aliyun.com/repository/public</url>
        </repository>
    </repositories>
    <dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.9</version>
    </dependency>
    </dependencies>
</project>
<?xml version="1.0" encoding="UTF-8" ?>
<!--文件名可以任意,文件类型一定要是xml文件-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--mybatis.org官网-入门里copy dtd -->
<configuration>
    <settings>
        <!--可以把数据库中的字段如goods_id ==>goodsId -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="dev">
        <!--default属性设置默认使用的数据库-->
        <environment id="dev">
            <!--采用JDBC对数据库对事务commit/rollback-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--使用连接池对数据进行管理-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="abc123456"/>
            </dataSource>
        </environment>
        <environment id="dev1">
            <!--采用JDBC对数据库对事务commit/rollback-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--使用连接池对数据进行管理-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/babytun?useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="abc123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers/student.xml"/>
        <mapper resource="mappers/classes.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">
<mapper namespace="classes">
    <resultMap id="rmClassesDetails" type="com.imooc.mybatis.entity.Classes">
        <id column="id" property="id"></id>
        <collection property="student" select="student.selectStuByClassno" column="classno" />
    </resultMap>
    <select id="selectClassesDetailsByClassno" parameterType="String" resultMap="rmClassesDetails">
       select * from school.classes where classno = #{value}
   </select>
</mapper>
<?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">
<mapper namespace="student">
        <select id="selectStuByClassno" parameterType="String" resultType="com.imooc.mybatis.entity.Student">
               select * from school.student where classno = #{value}
        </select>
        <resultMap id="rmStudents" type="com.imooc.mybatis.entity.student">
                <id column="id" property="id"></id>
                <result column="classno" property="classno"/>
                <association property="classes" select="classes.selectClassesDetailsByClassno"
                             column="classno"></association>
        </resultMap>
        <select id="selectClassBySex" parameterType="String" resultMap="rmStudents">
            select * from school.student where sex = #{value}
        </select>
</mapper>
package com.imooc.mybatis.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
public class MyBatisUtils {
    //利用static属于类不属于对象,且全局唯一
    private static SqlSessionFactory sqlSessionFactory;
    //利用静态块在初始化类时
    static {
        Reader reader;
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            //如果xml文件名写错了,会出现IOException:Counld not find resouce mybatis1-config.xml
            //也会出现NoClassDefFoundError:Could not initialize class com.imooc.mybatis.utils.MyBatisUtils
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            //初始化错误时,通过抛出异常ExceptionInInitializerError通知调用者
            throw new ExceptionInInitializerError(e);
        }
    }
    public static SqlSession openSession(){
        return sqlSessionFactory.openSession();
    }
    public static void closeSession(SqlSession session){
        if(session != null) {
            session.close();
        }
    }
}
package com.imooc.mybatis.entity;
import java.util.ArrayList;
import java.util.List;
public class Classes {
    Integer id;
    String classno;
    String name;
    String major;
    List<Student> student;
    public List<Student> getStudent() {
        return student;
    }
    public void setStudent(List<Student> student) {
        this.student = student;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getClassno() {
        return classno;
    }
    public void setClassno(String classno) {
        this.classno = classno;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}
package com.imooc.mybatis.entity;
import java.util.List;
public class Student {
    Integer id;
    String  stuno;
    String  stuname;
    String sex;
    String classno;
    Classes classes;
    public Classes getClasses() {
        return classes;
    }
    public void setClasses(Classes classes) {
        this.classes = classes;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getStuno() {
        return stuno;
    }
    public void setStuno(String stuno) {
        this.stuno = stuno;
    }
    public String getStuname() {
        return stuname;
    }
    public void setStuname(String stuname) {
        this.stuname = stuname;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getClassno() {
        return classno;
    }
    public void setClassno(String classno) {
        this.classno = classno;
    }
}
import com.imooc.mybatis.entity.Classes;
import com.imooc.mybatis.entity.Student;
import com.imooc.mybatis.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class Test {
    @org.junit.Test
    public void testSelectByClassno() throws Exception {
        SqlSession session = null;
        try {
            session = MyBatisUtils.openSession();
            List<Classes> classesList = session.selectList("classes.selectClassesDetailsByClassno", "Class001");
            for (Classes classes : classesList){
                System.out.println(classes.getName()+":");
                for(Student stu :classes.getStudent()){
                    System.out.println(stu.getStuno()+"-"+stu.getStuname()+"-"+stu.getSex()+"-"+stu.getClassno());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            MyBatisUtils.closeSession(session);
        }
    }
  @org.junit.Test
    public void testSelectClassBySex() throws Exception {
        SqlSession session = null;
        try {
            session = MyBatisUtils.openSession();
            List<Student> students= session.selectList("student.selectClassBySex","男");
            for(Student stu: students){
               System.out.println(stu.getSex()+"-"+stu.getStuname()+"-"+stu.getClasses().getName());
           }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            MyBatisUtils.closeSession(session);
        }
    }
}


正在回答

登陆购买课程后可参与讨论,去登陆

2回答

同学你好,

1、测试运行上述贴出代码是正确的,非常棒,继续加油~

2、理解是正确的,如果配置文件名称写错,就会出现上述两个异常

祝学习愉快~

  • 晓舟 提问者 #1

    https://img1.sycdn.imooc.com//climg/6243c20908a07eaf03240600.jpg


      @org.junit.Test
        public void testSelectClassesBySex() throws Exception {
            SqlSession session = null;
            try {
                session = MyBatisUtils.openSession();
                List<Student> students= session.selectList("student.selectClassesBySex","男");
                for(Student stu: students){
                   System.out.println(stu.getSex()+"-"+stu.getStuname()+"-"+stu.getClasses().getName());
               }
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            } finally {
                MyBatisUtils.closeSession(session);
            }


    https://img1.sycdn.imooc.com//climg/6243c19d0828871500000000.jpg

    这里有问题,但没查出原因


    package com.imooc.mybatis.utils;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import java.io.IOException;
    import java.io.Reader;
    public class MyBatisUtils {
        //利用static属于类不属于对象,且全局唯一
        private static SqlSessionFactory sqlSessionFactory;
        //利用静态块在初始化类时
        static {
            Reader reader;
            try {
                reader = Resources.getResourceAsReader("mybatis-config.xml");
                //如果xml文件名写错了,会出现IOException:Counld not find resouce mybatis1-config.xml
                //也会出现NoClassDefFoundError:Could not initialize class com.imooc.mybatis.utils.MyBatisUtils
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            } catch (IOException e) {
                e.printStackTrace();
                //初始化错误时,通过抛出异常ExceptionInInitializerError通知调用者
                throw new ExceptionInInitializerError(e);
            }
        }
        public static SqlSession openSession(){
            return sqlSessionFactory.openSession();
        }
        public static void closeSession(SqlSession session){
            if(session != null) {
                session.close();
            }
        }
    }


    2022-03-30 10:37:32
  • 晓舟 提问者 #2

    配置文件名都是正确的

    2022-03-30 10:41:28
  • 好帮手慕小脸 回复 提问者 晓舟 #3

    同学你好,

    1、参考同学的目录结构,以及测试运行代码是可以的,如下所示:

    https://img1.sycdn.imooc.com//climg/6243c6eb09ae24b302860123.jpg

    2、建议同学看一下student.xml中如下查询语句的id是否与方法中调用的相匹配

    https://img1.sycdn.imooc.com//climg/6243c74809d86e2715370219.jpg

    3、student.xml文件中有一处类名小写了,要注意修改:
    spacer.gifhttps://img1.sycdn.imooc.com//climg/6243c9580838ccce06500203.jpg

    4、上述贴出报错信息指向了Test类的44行,应该是关闭SqlSession的代码,建议同学先将这行代码注释掉,查看具体错误信息。并根据报错信息检查配置文件。

    祝学习愉快~

    2022-03-30 10:59:54
晓舟 提问者 2022-03-30 10:34:08
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师