Cover: Luo Xiaoxi
Author: Pan Pan
Mybatis is a persistent layer framework, flexible and easy to use, especially popular.
preface
Mybatis series full solution, we are expected to prepare 16 articles, let us understand the basic picture of Mybatis, really from the entry to the hand, from the hand to master, this first article, we start.
Mybaits Series full solutions (continuously updated)
- Mybatis series full solution (a) : handwriting a set of persistent layer frame
- Mybatis series full solution (2) : Mybatis introduction and environment construction
- Mybatis series full solution (3) : Mybatis simple CRUD use introduction
- Mybatis series full solution (four) : the most complete network! Mybatis configuration file XML overview
- Mybatis series full solution (5) : the most complete network! Mybatis Mapper mapping file
- Mybatis series full solution (6) : Mybatis most core API you know how many?
- Mybatis series full solution (7) : Dao layer two ways to achieve
- Mybatis series full solution (8) : Mybatis dynamic SQL
- Mybatis series full solution (9) : Complex mapping of Mybatis
- Mybatis series full solution (10) : Mybatis annotation development
- Mybatis series full solution (11) : Mybatis cache full solution
- Mybatis plug-in development
- Mybatis series full solution (13) : Mybatis code generator
- Spring integrates Mybatis
- Mybatis series full solution (15) : SpringBoot integrated Mybatis
- Mybatis series full solution (16) : Mybatis source code analysis
directory
1. What is Mybatis
2, Mybatis past life
3. Advantages of Mybatis
4. Overall architecture diagram of Mybatis
5. Environment construction
6, summary
What is Mybatis
Let’s have a look at the official website introduction, Mybatis official website: mybatis.org/mybatis-3/
MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.
Roughly translated:
MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can use simple XML or annotations to configure and map native types, collection interfaces, and Java’s Plain Old Java Objects (POJOs) to records in the database.
My current understanding is that Mybatis abstracts a large number of JDBC redundant codes, and provides a flexible and easy-to-use API to interact with the database based on the object relational mapping model.
Mybatis past life and present life
Everything has the past, before we talked about a JDBC introduction and practical application, and analyzed and compared the difference between JDBC and persistence layer framework, because JDBC requires developers to write too much code, operation of all objects, both troublesome and especially prone to error, so in our actual development rarely directly use JDBC programming, Therefore, it is particularly important for ORM to appear on the stage. The full name of ORM is Object/Relation Mapping: the abbreviation of object-relational Mapping.
ORM model, simply put, is the mapping relationship model between database tables and simple Java objects. With the ORM framework, applications no longer access the underlying database directly, but operate on persistent objects in an object-oriented manner, and the ORM framework translates these object-oriented operations into the underlying SQL operations. ORM framework to achieve the effect: save, modify, delete persistent objects, and other operations, to the database operation.
SUN initially introduced the Java EE Server-side Component Model (EJB), but it was quickly phased out due to the complexity of EJB configuration and its limited applicability. Later, Hibernate, the ORM persistence layer framework with high encapsulation degree, high development efficiency and full table mapping, emerged and became the preferred Java ORM model framework at that time. However, with the rapid development of the Internet and the continuous emergence of complex business scenarios, Hibernate has gradually exposed its shortcomings in many aspects: insufficient flexibility, inability to assemble different SQL according to different conditions, poor support for multi-table association and complex SQL queries, poor SQL optimization and performance, inconvenience brought by full table mapping and so on.
Therefore, Mybatis framework emerges at the right moment, which makes up for the deficiency of Hibernate. It is not only simple and easy to use, but also highly flexible, optimized and easy to maintain, and has become the preferred framework for large Internet projects.
Mybatis unofficial history: Mybatis, formerly iBATIS, is an open source project initiated by Clinton Begin in 2001. It initially focused on the development of cryptographic software, and later developed into a Java-based persistence layer framework. In 2004, Clinton donated iBATIS ‘name and source code to the Apache Software Foundation, and over the next six years, the world of open source software has changed dramatically, with all development practices, infrastructure, licensing, and even database technology completely transformed. In June 2010, the core development team migrated the project from Apache Software Foundation to Google Code. As the development team moved to Google Code, Ibatis3. x was officially renamed as Mybatis. The code was migrated to Github in November 2013.
The advantage of the Mybatis
Mybatis is a semi-automated persistence layer framework. For developers, core SQL still needs to be optimized by themselves. SQL and Java coding are separated, and functional boundaries are clear, with one focusing on business and one on data.
The blue area is the function support of Mybatis framework, and the red area is the actual 2 steps of the engineering project with Mybatis framework:
There are many persistence frameworks implemented in Java, and MyBatis is popular for the following reasons:
1. It eliminates a lot of JDBC redundant code
2. It has a low learning curve
3. It works well with traditional databases
It can accept SQL statements
It provides integration support with the Spring and Guice frameworks
It provides integration support with third-party caching libraries
7. It introduces better performance
Mybatis overall architecture diagram
Environment set up
The Java development environment, Mysql database, and Maven environment have been installed by default.
Mybatis development and environment building, we first start the experience, the steps are as follows:
1. Create maven project
2, Add MyBatis repository coordinates (not maven project)
Create table user
4. Write the User entity class
5. Write the mapping file usermapper.xml
6. Compile the core file SQLMAPconfig.xml
7. Write test classes
1. Create maven project
2. Add MyBatis warehouse coordinates
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<! - mybatis coordinates - >
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<! -- Mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<! -- Unit test coordinates -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<! -- Log coordinates -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
Copy the code
Create table user
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`birthday` varchar(50) DEFAULT NULL.PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
Copy the code
4. Write the User entity class
package com.panshenlian.pojo;
/ * * *@Author: panshenlian
* @Description: user entity *@Date: Create in 2:08 2020/11/28
*/
public class User {
private int id;
private String username;
private String password;
private String birthday;
public int getId(a) {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername(a) {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword(a) {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBirthday(a) {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
@Override
public String toString(a) {
return "User{" +
"id=" + id +
", username='" + username + '\' ' +
", password='" + password + '\' ' +
", birthday='" + birthday + '\' ' +
'} '; }}Copy the code
5. Write the mapping file usermapper.xml
<! DOCTYPEmapper
PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userMapper">
<select id="findAll" resultType="com.panshenlian.pojo.User">
select * from User
</select>
</mapper>
Copy the code
6. Compile the core file SQLMAPconfig.xml
<! DOCTYPEconfiguration 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" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="/UserMapper.xml" />
</mappers>
</configuration>
Copy the code
7. Write test classes
package com.panshenlian.service;
import com.panshenlian.pojo.User;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/ * * *@Author: panshenlian
* @Description: Experience testing *@Date: Create in 2:21 2020/11/28
*/
public class MybatisTest {
@Test
public void testQueryUser01(a) throws IOException {
// Load the core configuration file
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get the sqlSession factory object
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// Get the sqlSession object
SqlSession sqlSession = sqlSessionFactory.openSession();
// Execute the SQL statement
List<User> userList = sqlSession.selectList("userMapper.findAll");
// Print the result
for (User user : userList) {
System.out.println(user);
}
// Release resourcessqlSession.close(); }}Copy the code
Finally, the Junit unit test was passed, and the results were as expected:
Engineering structure reference:
conclusion
Through the introduction of this paper, we also started to do a test project for entry experience, and basically had a preliminary understanding of Mybatis. Meanwhile, we compared JDBC and Hibernate, and made clear the mission of Mybatis birth and inherent advantages. In the follow-up, we will continue to explain in depth and sort out and analyze the various knowledge veins of Mybatis.
After this article, we will talk about “Mybatis simple CRUD use introduction”.
BIU ~ the article continues to update, wechat search “Pan Pan and his friends” the first time to read, there are surprises at any time. This article will be included on GitHub github.com/JavaWorld, hot technology, framework, surface, solution, we will be the most beautiful posture in the first time, welcome Star.