找不到mybatis-config.xml
尝试maven idea:module,不是模块构造问题
尝试检验pom.xml,在编译模块添加了解析resources内容依旧不行
<?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.example</groupId>
<artifactId>untitled1</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- MyBatis的jar包配置 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- MySQL驱动包的配置 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version> <!-- 更新为与你的MySQL服务器版本兼容的版本 -->
</dependency>
</dependencies>
<!-- 配置以下信息,是src/main/java目录下有xml文件 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
再回看一下源代码
package com.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 com.mybatis.po.MyUser;
public class MyBatisTest {
public static void main(String[] args) {
try {
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
SqlSession ss = ssf.openSession();
MyUser mu = ss.selectOne("com.mybatis.mapper.UserMapper.selectUserById", 1);
System.out.println(mu);
MyUser addmu = new MyUser();
addmu.setUname("张三");
addmu.setUsex("男");
ss.insert("com.mybatis.mapper.UserMapper.addUser",addmu);
MyUser updatemu = new MyUser();
updatemu.setUid(1);
updatemu.setUname("杨婉莹");
updatemu.setUsex("女");
ss.update("com.mybatis.mapper.UserMapper.updateUser", updatemu);
ss.delete("com.mybatis.mapper.UserMapper.deleteUser", 3);
List<MyUser> listMu = ss.selectList("com.mybatis.mapper.UserMapper.selectAllUser");
for (MyUser myUser : listMu) {
System.out.println(myUser);
}
ss.commit();
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
关键在于找到resource
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
在网上也有resource目录突然罢工不生效,也就是检测不到resource目录,这边也是层级的问题
需要把resource目录设置为资源根目录,这本应该是创建项目时默认的,但是失效了我们需要重新设置一下
右键resources目录将目录标记为测试资源根目录,当图标右下角出现三条黄色横杠时就成功了。