In this article, I will introduce the framework principles of mybatis and the introductory program of mybatis to realize the user's addition, deletion, modification and inspection. What are its advantages and disadvantages and what relationship exists between mybatis and hibernate. I hope it will be helpful to my friends. If there are any shortcomings, please give me some advice.
What is mybatis?
MyBatis is an open source project of apache. In 2010, this project was moved from apache software foundation to Google code and was renamed MyBatis. Migrated to Github in November 2013.
MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manual setting parameters and decimating result sets. MyBatis uses simple XML or annotations to configure and map primitives, mapping interfaces and Java POJOs (Plain Old Java Objects) into records in the database. Simply put, mybatis is a persistent layer framework. Mybatis allows the program to focus on SQL and freely and flexibly generate SQL statements that meet the needs through the mapping method provided by mybatis. Mybatis can automatically input map the input parameters to prepareStatement and flexibly map the query result set into Java objects.
Next, let’s understand the framework principle of mybatis through a picture:
Framework architecture explanation:
a. Loading configuration file: The configuration comes from two places, one is the configuration file and the other is the annotation of Java code. The configuration information of SQL is loaded into MappedStatement objects (including the passed parameter mapping configuration, executed SQL statements, and result mapping configuration) and stored in memory.
b. SQL parsing: When the API interface layer receives the call request, it will receive the id of the incoming slq and the incoming object (can be map or basic data type). Mybatis will find the corresponding MappedStatement based on the id of the sql, and then parse the MappedStatement based on the incoming parameter object. After parsing, you can get the sql statements and parameters to be executed in the end.
c. SQL execution: Take the final SQL and parameters to the database for execution, and obtain the results of operating the database.
d. Result mapping: convert the results of the operating database according to the mapping configuration, which can be converted into HashMap, JavaBean or basic data type, and return the final result.
Mybatis Getting Started Program Analysis
Next, the editor will introduce the specific requirements in combination with the demo, and the requirements are as follows:
Query user information based on user id;
Query user information fuzzyly based on user name;
Add, delete, and update users.
The first step is to create various packages and classes, the project directory is as follows:
The second step is to write the content in SqlMapConfig.xml, and configure the running environment, data source, transactions, etc. of mybatis. The code looks like this:
<span style="font-family:Comic Sans MS;font-size:18px;"><?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> <!-- After the spring is integrated, the environments configuration will be abolished --> <environments default="developent"> <!-- Use jdbc transaction management, transaction control is by mybatis --> <transactionManager type="JDBC"/> <!-- Database connection pool, managed by mybatis --> <dataSource type="POLLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environments> <!-- Loading the map file --> <mappers> resource="sqlmap/User.xml"/> </mappers> </configuration> </span>The third step is to write the content in User.java, as shown below:
<span style="font-family:Comic Sans MS;font-size:18px;">package cn.itcast.mybatis.po; import java.util.Date; /** * * <p>Title: User</p> * <p>Description:User po </p> * @author Ding Guohua* @date July 31, 2016 15:39:04 * @version 1.0 */ public class User { //The attribute name corresponds to the fields of the database table private int id; private String username;// User name private String sex;// Gender private Date birthday;// birthday private String address;// address public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } } </span>Step 4: To implement the function of adding, deleting, modifying and searching, first write the content in User.xml, as shown below:
<span style="font-family:Comic Sans MS;font-size:18px;"><?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"> <!-- The namespace namespace is the function of classifying the SQL management and understanding the isolation of SQL Note: using the mapper proxy method to develop, namespace plays a special and important role --> <mapper namespace="test"> <!-- Configure many SQL statements in the mapping file --> <!-- Requirements: Query the records of the user table through id --> <!-- Execute database query id: Identify the SQL in the mapping file Encapsulate the SQL statement into a mappedStatement object, so the id is called the id parameterType: Specify the type of the input parameter, here specify the int type #{} to represent a placeholder symbol #{id}: where the id represents the parameter receiving the input, and the parameter name is id. If the input parameter is a simple type, the parameter name in #{} can be arbitrary, and can be value or other names resultType: Specify the type of the mapped java object of the output result of the sql, and select specify resultType to represent the java object mapped to a single record. --> <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User"> SELECT * FROM USER WHERE id=#{value} </select> <!-- fuzzy query user information based on the user name, multiple resultTypes may be returned: the specified is the java object type ${} mapped by the single-hand record: It means splicing the sql string, and splicing the received parameters into SQL without any modification. Use ${} to splice sql, causing SQL to inject ${value}: to receive the content of the input parameters. If the incoming type is a simple type, you can only use value in ${} --> <select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User"> SELECT * FROM USER WHERE username LIKE '%${value}%' </select> <!-- Add user parameterType: specify that the input parameter type is pojo (including user information) Specify the attribute name of the pojo in #{}, receive the attribute value of the pojo object, mybatis obtains the attribute value of the object through OGNL-> <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User"> <!-- Return the primary key of the inserted data and return it to the user object SELECT LAST_INSERT_ID(): Get the primary key value recorded just inserted into it, which is only applicable to self-increment primary key keyProperty: Set the primary key value of the query to the property of the object specified by parameterType: SELECT LAST_INSERT_ID() execution order, relative to the insert statement, its execution order resultType: Specify the result type of SELECT LAST_INSERT_ID()--> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSER_ID() </selectKey> insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address}) <!-- Use mysql's uuid() function to generate the primary key execution process. First, get the primary key through uuid, set the primary key to the id attribute of the user object, and then secondly, when insert is executed, remove the id attribute value from the user object--> <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String"> SELECT uuid() </selectKey> insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address}); </insert> <!-- To delete a user to delete a user based on the id, you need to enter the id value--> <delete id="deleteUser" parameterType="java.lang.Integer"> delete from user where id=#{id} </delete> <!-- To update user analysis based on the id: The id of the user needs to be passed in The user needs to be updated with the parameterType specifies the user object, including the id and update information. Note: the id must exist #{id}: Get the id attribute value from the input user object --> <update id="updateUser" parameterType="cn.itcast.mybatis.po.User"> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} </update> </mapper></span>Step 5: Write the specific method as follows:
<span style="font-family:Comic Sans MS;font-size:18px;">package cn.itcast.mybatis.first; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import cn.itcast.mybatis.po.User; public class MybatisFirst { // Query user information based on id and get a record result @Test public void findUserByIdTest() throws IOException { // mybatis configuration file String resource = "SqlMapConfig.xml"; // Get configuration file stream InputStream inputStream = Resources.getResourceAsStream(resource); // Create a session factory and pass in mybatis configuration file information SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); // Get SqlSession through the factory SqlSession sqlSession = sqlSessionFactory.openSession(); // Operate the database through SqlSession// The first parameter: the id of the statement in the map file is equal to =namespace+"."+ id of the statement // The second parameter: specify the parameter of the parameterType type matched in the map file // sqlSession.selectOne result is an object of the resultType type matching in the map file // selectOne query to find a record User user = sqlSession.selectOne("test.findUserById", 1); System.out.println(user); // Release the resource sqlSession.close(); } // Fuzzy query the user list based on the user name @Test public void findUserByNameTest() throws IOException{ //mybatis configuration file String resource ="SqlMapConfig.xml"; // Get the configuration file InputStream inputStream = Resources.getResourceAsStream(resource); //Create a session factory and pass in mybatis configuration file information SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //Get SqlSession through the factory SqlSession sqlSession = sqlSessionFactory.openSession(); //The user in List in List is the same as the type specified by the German resultType in the mapping file List<User> list = sqlSession.selectList("test.findUserByName","Xiao Ming"); System.out.println(list); sqlSession.close(); } public void insertUserTest() throws IOException{ //mybatis configuration file String resource ="SqlMapConfig"; //Get configuration file stream InputStream inputStream = Resources.getResourceAsStream(resource); //Create a session factory and pass in mybatis configuration file information SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //Get sqlsession through the factory SqlSession sqlSession = sqlSessionFactory.openSession(); //Insert the user object User user = new User(); user.setUsername("Ding Guohua"); user.setBirthday(new Date()); user.setSex("1"); user.setAddress("Anhui Hefei"); //The user in the list and the type specified by the resultType in the mapping file are always sqlSession.insert("test.insertUser",user); //Submit things sqlSession.commit(); //Close the session sqlSession.close(); } //Delete user information based on id @Test public void deleteUserTest() throws IOException{ //mybatis configuration file String resource = "SqlMapConfig.xml"; //Get configuration file stream InputStream inputStream = Resources.getResourceAsStream(resource); //Create a factory and pass in mybatis configuration file information SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //Get SqlSession through the factory SqlSession sqlSession = sqlSessionFactory.openSession(); //Passing incoming id delete user sqlSession.delete("test.deleteUser",39); //Submit things sqlSession.commit(); //Close the session sqlSession.close(); } //Update user information @Test public void updateUserTest() throws IOException { // mybatis configuration file String resource = "SqlMapConfig.xml"; // Get configuration file stream InputStream inputStream = Resources.getResourceAsStream(resource); // Create a session factory and pass in mybatis configuration file information SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); // Get SqlSession through the factory SqlSession sqlSession = sqlSessionFactory.openSession(); //Update user user = new User(); //Update id user.setId(41); user.setUsername("Ding Guohua"); user.setBirthday(new Date()); user.setSex("2"); user.setAddress("Anhui Hefei"); sqlSession.update("test.updateUser", user); // commit transaction sqlSession.commit(); // close session sqlSession.close(); } } </span>Pros and Cons of mybatis
advantage:
a. Easy to get started and master.
b. SQL is written in XML, which facilitates unified management and optimization.
c. Decouple SQL and program code.
d. Provide mapping tags to support orm field relationship mapping between objects and databases
e. Provide object relationship mapping tags to support object relationship construction and maintenance
f. Provide XML tags and support writing dynamic SQL.
shortcoming:
a. SQL workload is very high, especially when there are many fields and many related tables.
b. SQL depends on the database, resulting in poor database portability.
c. Since the tag id in the xml must be unique, the methods in DAO do not support method overloading.
d. The DAO layer is too simple, and the workload of object assembly is relatively large.
e. Improper use of cache can easily generate dirty data.
Comparison between mybatis and hibernate
Similarities: Hibernate and mybatis can generate SessionFactory from the xml configuration file through SessionFactoryBuilder, and then generate Session from SessionFactroy. Finally, Session starts executing things and SQL statements. The life cycles of SessionFactoryBuilder, SessionFactory, and Session are almost the same.
Differences:
mybatis: small, convenient, efficient, simple, direct, semi-automatic;
hibernate: powerful, convenient, efficient, complex, bends, fully automatic;
mybatis:
a. Simple to get started, learn and use it as soon as possible. It provides automatic object binding function for database queries, and continues a lot of SQL usage experience. It is perfect for projects that do not have such high object model requirements.
b. More detailed SQL optimization can be performed and query fields can be reduced.
c. The disadvantage is that the framework is still relatively simple and the functions are still missing. Although the data binding code is simplified, the entire underlying database query actually has to be written by itself, the workload is relatively large, and it is not easy to adapt to rapid database modification.
d. The secondary caching mechanism is poor.
hibernate:
a. Strong functions, good database irrelevance, and strong O/R mapping capabilities. If you are quite proficient in Hibernate and properly encapsulate Hibernate, then the entire persistence layer code of your project will be quite simple, the code that needs to be written is very high, the development speed is very fast, and it is very cool.
b. There is a better secondary caching mechanism, and third-party caching can be used.
c. The disadvantage is that the learning threshold is not low, and you must be proficient in it. How to design O/R mapping, how to balance the performance and object model, and how to use Hibernate well requires your experience and ability to be strong.
Let me give you a vivid metaphor:
mybatis: Mechanical tools are easy to use and can be used as soon as possible, but the work still needs to be done by yourself, but the tools are alive, so how to make them depends on me.
hibernate: Intelligent robot, but it is very expensive to develop it (learning, proficiency) and work can get rid of it, but only what it can do.
Editor's message: In this blog post, the editor mainly briefly introduced the basic knowledge of mybatis, including a simple demo of adding, deleting, modifying and searching, the advantages and disadvantages of mybatis, and the comparison between hibernate and mybatis. The similarities and differences between them. Mybatis simply means a persistence layer framework. Mybatis allows the program to focus on SQL, and freely and flexibly generate SQL statements that meet the needs through the mapping method provided by mybatis. Mybatis can automatically input the input parameters to prepareStatement, and flexibly map the query result set into Java objects.
The above is the introductory tutorial for the mybatis principle overview introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!