配置Mybatis后,创建SqlSession对象,此时程序运行到这里没有报错;但是当我配置了一个TestMapper.xml文件,将其url加载到mybatis-config.xml,再执行selectList语句,查询News对应的news表时,报了运行错误,一直查询不到结果。我的路径写的应该没问题呀,是格式还是其他的问题呢?报错内容:
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
—Error building SqlSession.
—The error may exist in src/com/stu/mybatis/TestMapper.xml
—Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration.
—Cause: java.net.MalformedURLException: no protocol: src/com/stu/mybatis/TestMapper.xml
public class TestMybatis {
public static void main(String[] args) throws FileNotFoundException {
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(new FileInputStream("mybatis-config.xml"));
SqlSession sqlSession= sqlSessionFactory.openSession(true);
List<News> list = sqlSession.selectList("selectNews");
for(News news:list){
System.out.println(news);
}
}
}
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--我只配置了驱动,数据库地址,用户,密码和下面的mapper路径-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载映射文件-->
<mapper url="src/com/stu/mybatis/TestMapper.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="TestMapper">
<select id="selectNews" resultType="com.stu.mybatis.News">
select * from News
</select>
</mapper>
参考GPT和自己的思路:根据你提供的错误信息和代码,可以看出错误可能是由于TestMapper.xml文件路径的问题导致的。错误信息中提到了java.net.MalformedURLException,这意味着 URL 链接不正确导致无法访问。在mybatis-config.xml中,你尝试使用相对路径进行加载mapper文件,但是路径格式不正确,应该使用file协议指定文件路径,格式如下:
<mapper url="file:src/com/stu/mybatis/TestMapper.xml"/>
另外,确认一下TestMapper.xml文件确实在指定的路径下,且文件名和后缀名没有误写。如果使用的是IDEA等集成开发环境,检查一下文件是否在src目录下,并且已经添加到了项目中。
希望我的答复能对你有所帮助,如果还有其他问题,请随时提出。