Written in the front: this note is part of the concept that I organized by following the madness teacher's video self-study. Please refer to Baidu Encyclopedia and official documents
System environment:
- jdk 12
- mysql 8.0.17
- maven 3.6.2
- IDEA
What is MyBatis
- MyBatis an excellent persistence framework
- MyBatis avoids almost all the JDBC code and manual setting of parameters and getting the result set
- MyBatis can use simple XML or annotation to configure and map native information, and map interface and Java entity class (Plain Old Java Objects, common Java objects) to records in database.
- Official documents of Mybatis: http://www.mybatis.org/mybatis-3/zh/index.html
- GitHub : https://github.com/mybatis/mybatis-3
What is persistence
- Persistence is a mechanism to transform program data between persistent state and transient state
- That is, to save data (such as objects in memory) to a storage device (such as disk) that can be permanently saved. The main application of persistence is to store objects in memory in database, disk file, XML data file and so on.
- JDBC is a persistence mechanism. File IO is also a persistence mechanism.
- Store the contents of the memory in the hard disk for permanent storage (compared with the hard disk, the memory is lost when the power is off)
What is persistence layer
- Code block to complete persistence work. --- > Dao layer [DAO (Data Access Object) data access object]
- In most cases, especially in enterprise applications, data persistence often means that the data in memory is stored on disk to be solidified, and the implementation process of persistence is mostly completed through various relational databases.
- But here is a word that needs special emphasis, that is, the so-called "layer". For application systems, data persistence is an essential part. That is to say, our system already has the concept of "persistence layer" naturally? It may be, but it may not be. The reason why we need to develop a concept of "persistence layer" instead of "persistence module" and "persistence unit" means that there should be a relatively independent logic layer in our system architecture, focusing on the implementation of data persistence logic
- Compared with other parts of the system, this level should have a clear and strict logical boundary. [to put it bluntly, it is used to operate the existence of database! ]
Why do we need MyBatis
- Replace the JDBC operation: Mybatis is to help the program ape store data in the database and get data from the database
- Avoid the phenomenon of repeated wheel building: traditional jdbc operation, there are many repeated code blocks. For example: encapsulation when data is taken out, establishment and connection of database, etc.. Through the framework, the repeated code can be reduced and the development efficiency can be improved
- MyBatis is a semi-automatic ORM framework (object relationship mapping) -- > object relationship mapping
- In the whole system development process, Mybatis is not a must, but with the help of Mybatis, we can make our project development easier.
Benefits of MyBatis
- Simple and easy to learn: small and simple, no third-party dependence
- Flexibility: no impact on the existing design of the application or database. sql is written in xml for unified management and optimization. Through sql statement, all the requirements of database operation can be satisfied.
- Decouple sql and program code: separate business logic and data access logic by providing DAO layer to make the system design clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.
- Provide xml tags
MyBatis first program
- Build database
CREATE DATABASE `mybatis`; USE `mybatis`; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(20) NOT NULL, `name` varchar(30) DEFAULT NULL, `password` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `user`(`id`,`name`,`password`) VALUES(1,'SKYID','123456'),(2,'Cai Xu Kong','123456');
- Import related Jar packages of Mybatis, Mysql and Junit through maven
<dependencies> <!-- mysql drive--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency> <!-- mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <!-- junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
- Write MyBatis core configuration file - mybatis-config.xml
<?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.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="12345678"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/sky/dao/UserMapper.xml"/> </mappers> </configuration>
property corresponds to mysql jar package, mysql URL address, mysql user name and password respectively
- Write Mybatis tool class according to official documents
package com.sky.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; public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { // Get SqlSessionFactory object with mybatis String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } // Get sqlsession sqlsession through SqlSessionFactory. Sqlsession contains all methods of sql operation for database public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
- Create POJO entity class
package com.sky.pojo; // Entity class public class User { private int id; private String name; private String password; //No reference method public User() { } //Have ginseng public User(int id, String name, String password) { this.id = id; this.name = name; this.password = password; } // get set method 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 getPassword() { return password; } public void setPassword(String password) { this.password = password; } // toString @Override public String toString() { return "User{" "id=" id ", name='" name '\'' ", password='" password '\'' '}'; } }
- Write Mapper interface file (UserMapper)
package com.sky.dao; import com.sky.pojo.User; import java.util.List; public interface UserMapper { public List<User> getUserList(); }
- Write Mapper's xml file (UserMapper.xml)
The interface file location of Mapper corresponding to namespace
<?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 Binding corresponding Mapper/DAO Interface--> <mapper namespace="com.sky.dao.UserMapper"> <select id="getUserList" resultType="com.sky.pojo.User"> select * from mybatis.User </select> </mapper>
- Write test Junit unit tests
package com.sky.dao; import com.sky.pojo.User; import com.sky.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserMapperTest { @Test public void selectUser() { SqlSession session = MybatisUtils.getSqlSession(); //Method 1: //List<User> users = session.selectList("com.kuang.mapper.UserMapper.selectUser"); //Method two: UserMapper mapper = session.getMapper(UserMapper.class); List<User> users = mapper.getUserList(); for (User user: users){ System.out.println(user); } session.close(); } }
- Run and test
Project structure
|-- mybatis-01 |-- mybatis-01.iml |-- pom.xml |-- src | |-- main | | |-- java | | | |-- com | | | |-- sky | | | |-- dao | | | | |-- UserMapper.java | | | | |-- UserMapper.xml | | | |-- pojo | | | | |-- User.java | | | |-- utils | | | |-- MybatisUtils.java | | |-- resources | | |-- mybatis-config.xml | |-- test | |-- java | |-- com | |-- sky | |-- dao | |-- UserMapperTest.java
Common problem
Cannot find Mapper.xml
This problem is generally caused by the fact that the. XML file is not placed under resources. Therefore, we can configure it in born.xml
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources>
Prompt the jdk version does not match
It is also a maven configuration problem. Check whether the environment configuration under born.xml is consistent with the native jdk version
<plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <!-- <version>3.7</version> Default to the latest--> <configuration> <source>12</source> <target>12</target> </configuration> </plugin> </plugins>
This article is based on the platform of blog one article multiple sending OpenWrite Release!