To configure Mybatis with the latest version of 2018 IDEA and MyBatis, I have searched online for most of the day without finding materials suitable for me as a novice, so I always fail to run and various errors are reported. So now I record a super simple MyBatis project in detail, which is the process from creating files to finding the first data, and paste codes. It is mainly some of the details that are hard to find on the Internet that the new appointee does not know, in order to facilitate themselves and the new appointee to fill in the gaps.

This is github address, you can see the directory structure: github.com/qylcx7758/I…

In fact, simply running the first project does not need WebApp at all, and POJO files and resource folders are not automatically generated, but created by themselves.

(Pit 1: This has puzzled me for a long time. Why can’t I find the file structure mentioned on the Internet? Here is the detailed file introduction.)

Create a project template: Maven + QuickStart

2.1

Pit 2: Java version do not use jdK9 above the version, I started using JDK10 error, as for how to IEDA JDK switch to other versions, Baidu on the line, there is a solution online; Both QuickStart and WebApp work, but I’m using the QuickStart template here.

Pit 3: do not create the project name with dashes, otherwise the file will not create the Class Class).



2.2 Maven configuration, all the same, there are many Maven tutorials online.



3. Initial configuration

3.1 Add Mysql driver and Mybatis dependency in the pop. XML file and click import in the lower right corner.



< the dependency > < groupId > mysql < / groupId > < artifactId > mysql connector - Java < / artifactId > < version > 6.0.6 < / version > </dependency> <! - * * * * * * * * * * * * * * * * * * * * * * Mybatis rely on * * * * * * * * * * * * * * * * * * * * * * -- > < the dependency > < groupId > org. Mybatis < / groupId > < artifactId > mybatis < / artifactId > < version > 3.4.4 < / version > < / dependency >Copy the code

3.2 At this time, the initial file structure is as follows. CsdnMybatis is my project name. The project structure is automatically generated.



Create a resource folder that is the same as the Java folder and set it to Resources Root.

Exception in thread “main” org.apache.ibatis…… The error.

(Pit 4: This resource folder is created by yourself and must be set to Resourcr Root, otherwise the code will not be able to access the XML configuration file, error)



4, the above is almost fixed, below is the configuration file information, write the file information in the Resource folder

4.1 Create two XML files in the Resource folder. The file structure is as follows:



4.2 In Mybatis-config, write the following code:

<? 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> <settings> <! MyBatis returns null by default when all columns of the returned row are empty --> <setting name="returnInstanceForEmptyRow" value="true"/>
    </settings>

    <environments default="development">

        <environment id="development"> <! JDBC's commit and rollback Settings are used, which rely on connections from data sources to manage transaction scopetype="JDBC"/ > <! -- Use datapool, reuse instance --> <dataSourcetype="POOLED"> <! --<property name="driver" value="com.mysql.jdbc.Driver"/>-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test? serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="TableDAO.xml"></mapper>
    </mappers>
</configuration>Copy the code





Here are four things to look out for,

Driver = com.mysql.jdbc.driver = com.mysql.jdbc.driver = com.mysql.jdbc.driver

The second tag, test, represents the user’s database, the third tag is the username and password,

Pit 6: The fourth tag corresponds to the tabledao.xml file you just created.



4.3 Write the following code in tabledao.xml:

<? 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="csdnMybatis">
    <select id="getWebsiteById" resultType="csdnMybatis.Twebsites">
        SELECT * FROM websites WHERE id = #{id};
    </select>

</mapper>Copy the code





This is just a simple search statement, there are also a lot of holes, there are too many ways to write on the Internet, but in this environment, I only tested my way of writing correctly, there are four things to pay attention to, I will use later, in my example directly like this:

Pit 7: Namespace =”csdnMybatis” corresponds to the folder where the file to be run later (TestMybatis– created later) is located; (If the file is deeper, you might need multiple layers, but not in this example.)

Pit 8: resultType= “csdnMybatis.Twebsites” corresponds to the class name created later;

Select * from websites where id=”getWebsiteById”;




Class files and body files

5.1 Create two files under csdnMybatis. The location corresponds to 4.3. The file structure is as follows:



5.2 In the Twebsite file, write the following code:

(It is not necessary to write the complete table field name, write a few simple will be ok)

package csdnMybatis;

public class Twebsites {
    private int id;
    private String name;


    public int getId() {returnid; } public voidsetId(int id){this.id=id; } public StringgetName() {
        return name;
    }
    public void setName(String name) { this.name = name; }}Copy the code

This code can be used for any table containing both id and name fields:



5.3 Body file, that is, write the following code in the running file:

package csdnMybatis;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class TestMybatis {
    public static void main(String[] args) throws IOException {
        String resource = "Mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();

        Twebsites c=  session.selectOne("getWebsiteById",2);
        System.out.println(c.getName());

        session.commit();
        session.close();
    }
}Copy the code

Errors may occur after 5.4



This requires the configuration of the running path





Run result, no error reported



6, new learning JAVA, write more than 2 hours, this is just an IDEA+MAVEN to run Mybatis simple project, if I can not run the simple project or have the wrong place, welcome to comment. As for typesetting, I will rearrange it if necessary.