问题描述:工程里有一个MyBatisUtil.java的工具类,封装用来对SqlSession进行openSqlSession和close的,
工具类中通过流获取mybatis-config.xml的配置文件
InputStream is= Resources.getResourceAsStream(“mybatis-config.xml”);
然后把相应的mapper.xml都写好了 select语句都没问题 进行测试时Junit里报java.lang.NoClassDefFoundError: Could not initialize class
cn.smbms.utils.MyBatisUtil
MyBatisUtil类代码如下
public
class MyBatisUtil {
private static SqlSessionFactory factory;
static{
InputStream is=null;
try {
is =
Resources.getResourceAsStream("mybatis-config.xml");
factory=new
SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated
catch block
e.printStackTrace();
}
}
}
public static SqlSession createSqlSession(){
return factory.openSession(true);
}
public static void closeSqlSession(SqlSession
sqlSession){
if(null!= sqlSession){
sqlSession.close();
}
}
}
经过多次检查MyBatisUtil,重新编绎等 问题还是没有得到解决
因为mapper.xml里写了多条select语句 ,再未添加最后一条select语句之前,测试是没有异常的,初步断定应该是最后一条语句有问题,然后把最后一条select语删除了,果然,测试其它的正常了,添上最后一条,测试其它的还是报之前的错误。最终确定到问题点了,最后写的select语句惹的祸,经过仔细检查,果然找到问题了
select
u.id,u.userName,u.gender from smbms_user u
and
u.userRole=#{userRole}
and
userName like CONCAT(’%’,#{userName},’%’)
其中resulType="user"属性给写错了 resultType 少写了一个t 导致MyBatisUtil加载时,其中的静态代码块在类加载时便会编绎执行,在编绎时读取mybatis-config.xml的配置文件,mybatis-config.xml中配置了mapper。Mapper中的select出错,最终导致MyBatisUtil.java的工具类加载失败
把mapper文件中错误改正,问题得到解决