When using VS Code for java+mybatis (non-Maven project) development, an error occurs: java.io.IOException: Could not find resource mybatis-config..

Problems using VS Code for java+mybatis development


question

Every MyBatis-based application is centered on an instance of SqlSessionFactory. SqlSessionFactoryBuilder can build a SqlSessionFactory instance from an XML configuration file or a pre-configured Configuration instance. Generally we use the following code to get a SqlSessionFactory instance:

String resource = "mybatis-config.xml";  // 该xml文件配置了一个Configuration
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

When using Idea for development, you only need to set the folder where the xml file is located as a resource folder. However, VS Code does not set it as a resource file (maybe there is, but I don't know).
When using Resources.getResourceAsXX(); in VS Code: java.io.IOException: Could not find resource mybatis-config.xml


Solution

There are two solutions

method 1

Use the overload of the build method to read the file directly, as follows:

// 直接读取文件方式

// 不使用Resources类帮我们读取xml文件,我们自己读取文件
InputStream is = new FileInputStream("MybatisDemo1/resources/mybatis-config.xml");
sqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

Method 2

Because Resources.getResourceAsXX reads the Sources directory (that is, the src directory) by default, you only need to put the xml file in the src directory (that is, the source code root path).
Insert image description hereThen you can use the following code

String configName = "mybatis-config.xml";
// 加载配置文件
InputStream resourceAsStream = Resources.getResourceAsStream(configName);
// 通过SqlSessionFactoryBuilder()构建SqlSessionFactory对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

Note: Maybe your Sources directory is not src. You can check your Sources directory through the following steps.
Open the resource manager and find JAVA PROJECTS in the resource manager . Put the mouse on it and several icons will appear on the right. Find the rightmost one . ..icon and click, click Configure Classpath in the pop-up menu , and then you can see your Sources directory.
Insert image description here


Summarize

It is recommended to use method 2, because when we develop, we may use <properties resource="jdbc.properties"></properties> in the mybatis-config.xml file to introduce another configuration file. If we use method 1, it will not be found. "jdbc.properties" file, even if the full path of jdbc.properties is written, an error will still be reported. Therefore, it is recommended to use method 2, which places both mybatis-config.xml and jdbc.properties in the src directory.

Guess you like

Origin blog.csdn.net/weixin_45345384/article/details/121242848