In the development of JAVA, a series of ORM frameworks emerged, JPA,Hibernate,Mybatis and Spring JDBC, this series,Mybatis will be studied in the future.
By studying the source code of Mybatis, the general architecture of Mybatis can be summarized as follows:
1. According to Mybatis source code, it is abstracted into three layers: basic support layer, core processing layer and interface layer
2. The basic support layer includes: data source, transaction management, logging, type conversion, caching, Bind, parser, etc
3. The core processing layer includes configuration parsing, configuration mapping, SQL parsing, SQL execution, result set mapping, plug-in, etc
4. The interface layer mainly provides JAVA APIS
In this article, the following problems will be solved based on the framework diagram:
Q1: What is the CRUD principle of Mybatis?
Q2: Why is semi-automated Mybatis more popular than automated Hibernate?
Q3: Why can Mybatis achieve loose coupling?
The CRUD principle of Mybatis
To solve this problem, let’s first look at the following code:
The function of this code is to query user information according to user_id. From the code, we can see that there are roughly five steps:
Step 1: Read the contents of mybatis global configuration file mybatis-config.xml
Step 2: Create the SqlSessionFactory session factory
Step 3: Create SQL session SqlSession according to SqlSessionFactory
Step 4: Perform the query operation
Mybatis-config.xml:
From the content, you can see that < Configuration > has three child nodes,<properties>,<environment> and <mapper> nodes.
So, what are these three nodes?
1. The properties node represents the properties node, which can be used to dynamically obtain resources from outside and make the obtained resources available for context use. Let’s look at the jdbc.properties content
. # mysql driver = com. Mysql. JDBC driver url = JDBC: mysql: / / 127.0.0.1:3306 / db_test? characterEncoding=UTF-8 username=root password=root
This is a database access parameter, so where do you refer to these parameters? <environment> child node.
例 句 : The environment node is used to configure the database test environment, development environment, etc. It is easy to see that the relevant child node placeholder reference dataSource
Properties node gets the content from jdbc.properties.
3. The mapper node is used to link the mapping file. Let’s take a look at the content of the mapping file:
! [insert picture description here] (https://img-blog.csdnimg.cn/20190619225440276.png?x-oss-process=image/watermark, type_ZmFuZ3poZW5naGVpdGk, sha dow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA2MzMyNjY=,size_16,color_FFFFFF,t_70)
Obviously, this is SQL add delete change check.
Through the above analysis, the three questions we raised at the beginning of the article can now be basically solved.
Q3: Why can Mybatis achieve loose coupling?
From the above analysis, we know that when mybatis is used as ORM framework development, our SQL statements are written in XML configuration files (such as userinfo-config.xml above), thus solving the traditional hard-coded
The strong coupling problem skillfully realizes the process from “hard coding” to “soft coding”.
In addition to the benefits of loose coupling, experienced developers should be aware that one major problem with hard coding is that when SQL code is changed, it needs to be recompiled, packaged, deployed, etc., before the program can run.
SQL statements implemented as configurable XML do not.
Q4: Why is semi-automated Mybatis more popular than automated Hibernate?
Hibernate is very powerful in terms of functionality, but it has some problems that are difficult to solve:
(1) High cost of learning. For novices, the time cost of learning Hibernate is much higher than Mybatis, so Mybatis is quick to learn
(2) the bulky. Hibernate’s powerful side reflects its unwieldy side
(3) Encapsulate SQL. Hibernate encapsulates SQL and only provides API interfaces to users, which is the root cause of its inflexibility
However, Mybatis will separate SQL and let users customize it.
Hibernate is automated because SQL generation, parsing, execution, and so on are automatically generated by Hibernate.
The reason why Mybatis is semi-automated is that SQL statements need user customization, SQL parsing, execution and other work is performed by Mybatis.
It can be said that while traditional JDBC is manual and Hibernate is automated, Mybati is a semi-automated ORM framework based on JDBC and Hibernate.
Two complete Mybatis CRUD
(1) Create a Web Application project
Open Intellij IDEA=>Create New Project=>Java Enterprise=> Select Web Application=>Next=>
Name the project MybatisCRUD=>Finish
(2) Import jar packages
The MySQL driver JAR package and Mybatis jar package are imported
Project Structure(Ctrl+Alt+Shift+S)=>Modules=>MybatisCRUD=> Select JARS or directories…
The import structure is as follows:
(3) Create test data
Create databaseDROP DATABASE IF EXISTS db_test CREATE DATABASE db_testDROP TABLE IF EXISTS User_Info
CREATE TABLE user_info (user_id INT(5) AUTO_INCREMENT PRIMARY KEY NOT NULL,# user id user_name VARCHAR(50) NOT NULL,# user name User_addr VARCHAR(100) NOT NULL
INSERT INTO user_Info(user_name,user_addr) VALUES('A',' sh-pudong '),('B',' sh-yangpu ') ('C','SH-QingPu'),('D','SH-XuHui')
Create UserInfo entity
Create three resource files
1.jdbc.property
. # mysql driver = com. Mysql. JDBC driver url = JDBC: mysql: / / 127.0.0.1:3306 / db_test? characterEncoding=UTF-8 username=root password=root
2.mybatis-config.xml
3.userInfo.config.xml
(6) the CRUD
1. Query
package demo.mybatis.Test; import demo.mybatis.entity.UserInfo; 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; import java.util.List; Public class TestMybatis {public static void main(String[] args) throws IOException {// Reading the configuration file. String resource ="demo/mybatis/resources/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSF = new SqlSessionFactoryBuilder().build(inputStream); SqlSession SqlSession sqlS = sqlsf.openSession (); List<UserInfo> List = sqls.selectList ("getUserInfoById", 2);
for (UserInfo user : list) {
System.out.println("UserName:" + user.getUser_name() + ",Addr:"+ user.getUser_addr()); } } finally { sqlS.close(); }}}Copy the code
2. Add
package demo.mybatis.Test; import demo.mybatis.entity.UserInfo; 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; import java.util.List; Public class TestMybatis {public static void main(String[] args) throws IOException {// Reading the configuration file. String resource ="demo/mybatis/resources/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSF = new SqlSessionFactoryBuilder().build(inputStream); SqlSession SqlSession sqlS = sqlsf.openSession (); // Add data try{UserInfo addUser = new UserInfo(); addUser.setUser_name("E");
addUser.setUser_addr("BJ-DongCheng");
sqlS.selectList("addUserInfo",addUser);
List<UserInfo> list=sqlS.selectList("listUserInfo");
for (UserInfo user :list){
System.out.println("UserName:"+user.getUser_name()+",Addr:"+user.getUser_addr()); } }finally { sqlS.close(); }}}Copy the code
3. Delete
package demo.mybatis.Test; import demo.mybatis.entity.UserInfo; 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; import java.util.List; Public class TestMybatis {public static void main(String[] args) throws IOException {// Reading the configuration file. String resource ="demo/mybatis/resources/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSF = new SqlSessionFactoryBuilder().build(inputStream); SqlSession SqlSession sqlS = sqlsf.openSession (); // Delete try{sqls.selectList ("delUserInfoById", 12); List<UserInfo> list=sqlS.selectList("listUserInfo");
for (UserInfo user :list){
System.out.println("UserName:"+user.getUser_name()+",Addr:"+user.getUser_addr()); } }finally { sqlS.close(); }}}Copy the code
(7) Code directory structure