1. Introduction
Environmental description:
jdk 8 +
MySQL 5.7.19
maven-3.6.1
IDEA
Before learning, you need to master:
JDBC
MySQL
Java Foundation
Maven
Junit
What is MyBatis
MyBatis is an excellent persistence layer framework
MyBatis avoids almost all JDBC code and the process of manually setting parameters and obtaining result sets
MyBatis can use simple XML or annotations to configure and map native information, and map the interface and Java entity class [Plain Old Java Objects] into records in the database.
MyBatis was originally an open source project ibatis of apache. In 2010, this project was migrated from apache to google code and renamed MyBatis.
Moved to Github in November 2013
Official documents of Mybatis: Introduction to mybatis – MyBatis 3
GitHub : https://github.com/mybatis/mybatis-3
Persistence
Persistence is a mechanism to convert program data between persistent state and transient state.
That is to save data (such as objects in memory) to a permanent storage device (such as disk). The main application of persistence is to store the objects in memory in the database, or in disk files, XML data files and so on.
JDBC is a persistence mechanism. File IO is also a persistence mechanism.
In life: refrigerate fresh meat and thaw it when eating. The same is true of canned fruit.
Why do you need persistence services? That is caused by the defect of memory itself
Data will be lost after memory power failure, but some objects cannot be lost anyway, such as bank accounts. Unfortunately, people can't guarantee that memory will never power down.
Memory is too expensive. Compared with external memory such as hard disk and optical disc, the price of memory is 2 ~ 3 orders of magnitude higher, and the maintenance cost is also high. At least it needs to be powered all the time. Therefore, even if the object does not need to be permanently saved, it will not stay in memory all the time due to the capacity limit of memory, and it needs to be persisted to cache to external memory.
Persistent layer
What is persistence layer?
Code block to complete persistence. --- > Dao layer [DAO (Data Access Object)]
In most cases, especially for enterprise applications, data persistence often means saving the data in memory to disk for solidification, and the implementation process of persistence is mostly completed through various relational databases.
However, there is a word that needs special emphasis, that is, the so-called "layer". For application systems, data persistence is an essential part. In other words, our system has a natural concept of "persistence layer"? Maybe, but maybe that's not the case. The reason why we want to separate the concept of "persistence layer" instead of "persistence module" and "persistence unit" means that there should be a relatively independent logical level 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 the database!]
Why do you need Mybatis
Mybatis is to help the program store data in the database and get data from the database
The traditional jdbc operation has many repeated code blocks, such as the encapsulation of data extraction, the establishment of database connection, 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
All things can still be done without Mybatis, but with it, all the implementation will be easier! There is no difference between high and low technology, only the people who use it
Advantages of MyBatis
Easy to learn: itself is small and simple. There is no third-party dependency. The simplest installation is just two jar files + several sql mapping files. It is easy to learn and use. Through documents and source code, you can fully master its design idea and implementation.
Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml for unified management and optimization. All requirements for operating the database can be met through sql statements.
Decouple sql and program code: by providing DAO layer, separate business logic and data access logic, so as 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 to support writing dynamic sql.
.......
2. MyBatis first program
1. Build experimental database
CREATE DATABASE `mybatis`; USE `mybatis`; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(20) NOT NULL, `name` varchar(30) DEFAULT NULL, `pwd` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`name`,`pwd`) values (1,'along','123456'),(2,'404rapper','123456'),(3,'long','123456');
2. Import MyBatis related jar package
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
3. Write MyBatis core configuration file
<?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=false&useUnicode=true&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/hls/dao/UserMapper.xml"/> </mappers> </configuration>
4. Write MyBatis tool class
package com.hls.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 { //The sqlSessionFactory object must be obtained to use Mybatis String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //Now that we have SqlSessionFactory, as the name suggests, we can get an instance of SqlSession from it. // SqlSession provides all the methods required to execute SQL commands in the database. public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
5. Create entity class
package com.hls.pojo; public class User { private int id; private String name; private String pwd; public User() { } public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } 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 + '\'' + '}'; } }
6. Writing Mapper interface classes
package com.hls.dao; import com.hls.pojo.User; import java.util.List; public interface UserDao { List<User> getUserList(); }
7. Write Mapper.xml configuration file
<?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="com.hls.dao.UserDao" > <select id="getUserList" resultType="com.hls.pojo.User"> select * from mybatis.user </select> </mapper>
8. Writing test classes
package com.hls.dao; import com.hls.pojo.User; import com.hls.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test(){ //The first step; Get SqlSession object SqlSession sqlSession = MybatisUtils.getSqlSession(); //Method 1: getMapper UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); for (User user:userList){ System.out.println(user); } //Close SqlSession sqlSession.close(); } }
Description of possible problems:
Maven static resource filtering problem
<!--stay bulit Medium configuration resources,To prevent the failure of resource export--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
Chinese cannot be written in mybatis-config.xml of resources