In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to decouple mybatis semi-automatically". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to decouple mybatis semi-automatically".
In the process of JAVA development, a series of ORM frameworks, JPA,Hibernate,Mybatis and Spring jdbc, have emerged. This series will study Mybatis in the future.
By studying the mybatis source code, the general architecture of mybatis can be summarized as follows:
1. According to the Mybatis source code, it is abstracted into three layers: basic support layer, core processing layer and interface layer.
two。 The basic support layer includes: data source, transaction management, log, type conversion, cache, Bind, parser, etc.
3. The core processing layer includes: configuration parsing, configuration mapping, SQL parsing, SQL execution, result set mapping, plug-ins, etc.
4. The interface layer mainly provides JAVA API.
In this article, based on this framework diagram, the following problems will be solved:
Q1: what is the CRUD principle of parsing mybatis with code?
Q2: why is semi-automated Mybatis more popular than automated Hibernate?
Why can Q3:Mybatis achieve loose coupling?
The CRUD principle of a mybatis
To solve this problem, let's take a look at the following code:
The function of the code is to query user information according to user_id. We can see from the code that it is roughly divided into five steps:
Step 1: read the contents of the global configuration file mybatis-config.xml of mybatis
Step 2: create a SqlSessionFactory session factory
Step 3: create a SQL session SqlSession based on SqlSessionFactory
Step 4: perform query operation
Public static void main (String [] args) throws IOException {/ / read the contents of the configuration file String resource = "demo/mybatis/resources/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource); / / create SqlSessionFactory SqlSessionFactory sqlSF = new SqlSessionFactoryBuilder (). Build (inputStream); / / create SqlSession SqlSession sqlS = sqlSF.openSession (); / / query try {/ / query user_id=2 records List list = sqlS.selectList ("getUserInfoById", 2) For (UserInfo user: list) {System.out.println ("UserName:" + user.getUser_name () + ", Addr:" + user.getUser_addr ());}} finally {sqlS.close ();}}
So, let's take a look at the Mybatis-config.xml content:
From the content, you can see that there are three child nodes, and nodes.
So, what exactly do these three nodes represent?
The 1.properties node represents the attribute node, which can be used to dynamically obtain resources from the outside, and the acquired resources are used for context. Let's take a look at the jdbc.properties content.
# mysqldriver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/db_test?characterEncoding=UTF-8username=rootpassword=root
You can see at a glance that these are parameters related to accessing the database, so where do you refer to these parameters? Child nodes.
2.environment node, environment node configuration node, such as database test environment, development environment, etc., it is easy to see that the placeholders of the relevant child nodes of dataSource refer to the content obtained by the properties node from jdbc.properties.
The 3.mapper node, the mapping node, is used to link the mapping file. Let's take a look at the contents of the mapping file:
SELECT user_name,user_addr FROM user_info SELECT user_name,user_addr FROM user_info WHERE user_id=# {user_id} INSERT INTO user_info (user_name,user_addr) VALUES (# {user_name}, # {user_addr}) DELETE FROM user_info WHERE user_id=# {user_id}
Obviously, this is the addition, deletion, modification and search of SQL.
Through the above analysis, the three problems we raised at the beginning of the article can now be basically solved.
Why can Q3:Mybatis achieve loose coupling?
From the above analysis, we know that when developing using mybatis as the ORM framework, our SQL statements are written in the xml configuration file (such as userInfo-config.xml above), thus solving the strong coupling problem of traditional hard coding and skillfully realizing the process from "hard coding" to "soft coding".
In addition to the benefits of loose coupling, experienced developers should be aware that there is a major problem with hard coding, that is, when the SQL code is changed, the program needs to be recompiled, packaged, deployed, and so on before the program can run, while SQL statements implemented through configurable xml are not needed.
Q4: why is semi-automated Mybatis more popular than automated Hibernate?
Functionally, Hibernate is very powerful, but there are some problems that are difficult to solve:
(1) the cost of learning is high. For beginners, the time cost of learning Hibernate is much higher than that of Mybatis, and Mybatis gets started very quickly.
(2) bulky. The powerful side of Hibernate reflects its bulky side.
(3) encapsulate SQL. Hibernate encapsulates SQL and only provides API interface to users, which is the root cause of its inflexibility.
However, mybatis separates SQL and allows users to customize it.
Through the comparison above, the reason why Hibernate is automated is that SQL generation, parsing, execution and so on are all generated automatically by Hibernate.
The reason why Mybatis is semi-automatic is that SQL statements need to be customized by users, and the parsing and execution of SQL are performed by Mybatis.
It can be said that traditional jdbc is manual, Hibernate is automated, and Mybati is a semi-automated ORM framework based on jdbc and Hibernate.
Biholonomic Mybatis CRUD
(1) create a Web Application project
Open Intellij IDEA= > Create New Project= > Java Enterprise= > check Web Application= > Next= >
Name the project MybatisCRUD= > Finish
(2) Import jar package
Here we mainly import two jar packages: the MySQL driver jar package and the Mybatis jar package.
Project Structure (Ctrl+Alt+Shift+S) = > Modules= > MybatisCRUD= > Dependencies= > Select JARS or directories...
The structure after successful import is as follows:
(3) create test data
# create a database DROP DATABASE IF EXISTS db_testCREATE DATABASE db_test# create a data table DROP TABLE IF EXISTS User_InfoCREATE TABLE user_info (user_id INT (5) AUTO_INCREMENT PRIMARY KEY NOT NULL,# user id user_name VARCHAR (50) NOT NULL,# username user_addr VARCHAR (100) NOT NULL # address) # insert simulation data INSERT INTO user_Info (user_name,user_addr) VALUES ('Achievement SHLI Pudong'), ('Bai Ling Ling SHLI Yangpu'), ('C' 'SH-QingPu'), (' Daozhongjinshou Xuhui')
(4) create a UserInfo entity
Package demo.mybatis.entity;public class UserInfo {String user_name; String user_addr; public String getUser_name () {return user_name;} public void setUser_name (String user_name) {this.user_name = user_name;} public String getUser_addr () {return user_addr;} public void setUser_addr (String user_addr) {this.user_addr = user_addr;}}
V) create three resource files
1.jdbc.property
# mysqldriver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/db_test?characterEncoding=UTF-8username=rootpassword=root
2.mybatis-config.xml
3.userInfo.config.xml
SELECT user_name,user_addr FROM user_info SELECT user_name,user_addr FROM user_info WHERE user_id=# {user_id} INSERT INTO user_info (user_name,user_addr) VALUES (# {user_name}, # {user_addr}) DELETE FROM user_info WHERE user_id=# {user_id}
(VI) 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 {/ / read configuration file contents String resource = "demo/mybatis/resources/mybatis-config.xml" InputStream inputStream = Resources.getResourceAsStream (resource); / / create SqlSessionFactory SqlSessionFactory sqlSF = new SqlSessionFactoryBuilder (). Build (inputStream); / / create SqlSession SqlSession sqlS = sqlSF.openSession (); / / query records of try {/ / query user_id=2 based on id List list = sqlS.selectList ("getUserInfoById", 2); for (UserInfo user: list) {System.out.println ("UserName:" + user.getUser_name () + ", Addr:" + user.getUser_addr ()) }} finally {sqlS.close ();}
two。 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 {/ / read configuration file contents String resource = "demo/mybatis/resources/mybatis-config.xml" InputStream inputStream = Resources.getResourceAsStream (resource); / / create SqlSessionFactory SqlSessionFactory sqlSF = new SqlSessionFactoryBuilder (). Build (inputStream); / / create 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 list=sqlS.selectList ("listUserInfo") For (UserInfo user: list) {System.out.println ("UserName:" + user.getUser_name () + ", Addr:" + user.getUser_addr ());}} finally {sqlS.close ();}
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 {/ / read configuration file contents String resource = "demo/mybatis/resources/mybatis-config.xml" InputStream inputStream = Resources.getResourceAsStream (resource); / / create SqlSessionFactory SqlSessionFactory sqlSF = new SqlSessionFactoryBuilder (). Build (inputStream); / / create SqlSession SqlSession sqlS = sqlSF.openSession (); / / delete try {sqlS.selectList ("delUserInfoById", 12); List list=sqlS.selectList ("listUserInfo"); for (UserInfo user: list) {System.out.println ("UserName:" + user.getUser_name () + ", Addr:" + user.getUser_addr ());}} finally {sqlS.close ();}
Thank you for reading, the above is the content of "how to semi-automatic decoupling of mybatis". After the study of this article, I believe you have a deeper understanding of the problem of semi-automatic decoupling of mybatis, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.