Write before: This article mainly records and shares the problems and configuration steps encountered in the process of configuring Mybatis by Idea.
Requirement: Maven has been configured!
catalogue
1.1 create a pure maven project
1.3 connecting database in IDEA
1.4 creating packages and files
2. Project xml file configuration
2.1 configure maven file pom.xml
2.2 configure Mybatis-config.xml in the resource file
1. Create Mybatis project
1.1 create a pure maven project
1.2 create database
Create a database named mybatis in mysql, and then create a user table:
CREATE DATABASE `mybatis`; USE `mybatis`; CREATE TABLE `user`( `id` INT(20) NOT NULL PRIMARY KEY, `name` VARCHAR(30), `pwd` VARCHAR(30) )ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO `user`(`id`,`name`,`pwd`) VALUES (1,'Zhang San','123456'), (2,'Li Si','123456'), (3,'Wang Wu','147258');
1.3 connecting database in IDEA
1.4 creating packages and files
In order to maintain consistency with me, it is recommended to create the same packages and files as me to better understand the configuration process and testing process.
1. Create Dao, pojo and utils packages in the main\java file and com.liu.dao package in the test\java directory
2. Create UserMapper interface and UserMapper.xml file under dao layer
package com.liu.dao; import com.liu.pojo.User; import java.util.List; public interface UserMapper { //Query all users List<User> getUserList(); }
<?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"> <!--namespace Namespace==Bind a corresponding Dao/Mapper Interface--> <mapper namespace="com.liu.dao.UserMapper"> <!--select Query statement--> <select id="getUserList" resultType="com.liu.pojo.User"> select * from mybatis.user </select> </mapper>
3. Create User.java (equivalent to JavaBean) in pojo and MybatisUtils.java (tool class) in utils
package com.liu.pojo; //Entity class public class User { private int id; private String name; private String pwd; public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
Tool class MybatisUtils
package com.liu.utils; 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 java.io.IOException; import java.io.InputStream; //Tool class SqlSessionFactory builds sqlSession public class MybatisUtils { //Promote scope private static SqlSessionFactory sqlSessionFactory; static { //Load at the beginning and operate according to the official code InputStream inputStream = null; try { //Step 1 of getting mybatis: get SqlSessionFactory object String resource="Mybatis-config.xml"; inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
4. Write test class
Create the UserDaoTest file under test\java\com.liu.dao
The code is as follows:
package com.liu.dao; import com.liu.pojo.User; import com.liu.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test(){ //Step 1: get the salSession object SqlSession sqlSession = MybatisUtils.getSqlSession(); //Execute SQL UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } //Close sqlSession sqlSession.close(); } }
The basic architecture of the above project has been completed. It mainly teaches you the configuration process. Let the code run first. As for the process and details, readers need to think carefully.
2. Project xml file configuration
2.1 configure maven file pom.xml
This is the jar package required to configure mybatis. Copy this code and refresh maven to complete the jar package import. Note that the version number of MySQL driver is the version number of MySQL installed on the computer. Version number query can be entered in DOS command:
mysql -h localhost -u username -p password
<!--Import dependency--> <dependencies> <!--MySQL drive--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
The following code is to synchronize the resource path with the file you created:
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
2.2 configure Mybatis-config.xml in the resource file
Problems needing attention in this Code:
1. Both default and id are development
2. The path of driver is different: the database version 5.7 is com.mysql.jdbc.Driver
The database is com.mysql.cj.jdbc.Driver after version 8.0
3.url configuration is prone to problems, and there are many configuration methods. Here I have been using:
jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&serverTimezone=UTC
4. The mapper must be configured. The address of the mapper is the xml configuration file that implements the interface under the dao layer. This file is used to write database code.
The code of Mybatis-config.xml is as follows:
<?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"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/liu/dao/UserMapper.xml"/> </mappers> </configuration>
3. Connection test
Test the query in the test class. You can find it on the console. The output result is displayed and the configuration is successful.
4. Frequently asked questions
1. Database query null pointer exception: check whether the configuration file under resource is correct
2. Character set error: cause: com.sun.org.apache.xerces.internal.impl.io.malformedbytesequenceexception: byte 2 of 2-byte UTF-8 sequence is invalid.
Reason: the filtering tag in pom.xml should be false (under Src / main / Java directory)
3. mapper tag content is not added in mybatis-config.xml configuration.
Configuration is not easy. I hope this article can help you~