Introduction to 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.
The term iBATIS comes from the combination of "internet" and "abatis", and is a Java-based persistence layer framework. iBATIS provides persistence layer frameworks including SQL Maps and Data Access Objects (DAO)
1. Required jar package
Here we discuss the use of MyBatis separately, just put the mybatis-xxxjar package.
If you use maven to build a project, you need to put the following configuration in the dependency of pom.xml:
<dependency><groupid>org.mybatis</groupid>mybatis</artifactid><version>3.2.2</version></dependency>
The company currently uses 3.2.2, and you can put the version number according to your own jar package.
If you are integrating with the corresponding framework, you need to put the integration package. For example, our company uses mybatis to integrate with spring.
You also need to add the mybatis-spring-xxx.jar package and decide based on the actual situation. Of course, database driver jar packages are also indispensable.
2. Build SqlSessionFactory from XML
Each MyBatis-based application is centered on an instance of SqlSessionFactory.
An instance of SqlSessionFactory can be obtained through SqlSessionFactoryBuilder.
SqlSessionFactoryBuilder can build an instance of SqlSessionFactory from an XML configuration file or a pre-customized configuration instance.
It is very simple to build an instance of SqlSessionFactory from an XML file. It is recommended to use the resource file under the classpath for configuration.
However, it can also be configured using any InputStream instance, including a file path in the form of a string or a file path in the form of a file:// URL.
MyBatis contains a tool class called Resources, which contains some practical methods that make it easier to load resource files from classpath or other locations.
For example:
String resource = "mybatis-config.xml";InputStream is = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
The XML configuration file (configuration XML) contains the core settings for the MyBatis system, including the data source for obtaining the database connection instance (DataSource)
and a Transaction Manager (TransactionManager) that determines the scope and control mode of transactions. The configuration file will be discussed in detail later.
For example:
<!--?xml version="1.0" encoding="UTF-8" ?--><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://192.168.200.12:3306/test_mybatis"><property name="username" value="root"><property name="password" value="root123"></property></property></property></datasource></transactionmanager></environment></environments><mappers><!-- Register the UserMainMapper.xml file. UserMainMapper.xml is located in the package com.lanhuigu.mybatis.map, so the resource is written as com/lanhuigu/mybatis/map/UserMainMapper.xml--><mapper resource="com/lanhuigu/mybatis/map/UserMainMapper.xml"></mapper></mappers></configuration>
The environment element body contains the configuration of transaction management and connection pooling. The mappers element contains a set of mapper mappers (the XML files of these mappers contain SQL code and mapping definition information).
3. Get SqlSession from SqlSessionFactory
Now that we have the SqlSessionFactory, we can get an instance of SqlSession from it. SqlSession fully contains all the methods required to execute SQL commands to a database.
You can directly execute mapped SQL statements through the SqlSession instance. For example:
SqlSessionFactory sqlSessionFactory = null;// XML build SqlSessionFactory factory instance SqlSession session = null;// Get the SqlSession object from the SqlSessionFactory factory instance try {String resource = "mybatis-config.xml";InputStream is = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);session = sqlSessionFactory.openSession();User user = session.selectOne("com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById", 1);System.out.println(user.getUsername());} finally {session.close();} There is no problem in executing mapping in this way, we can also perform mapping in a more concise way.
Use an interface that can reasonably describe parameters and return values for a given statement (for example, UserMainMapper.class),
Not only can you execute clearer and type-safe code now, but you don't have to worry about error-prone string literals and casts. For example:
SqlSession session = sqlSessionFactory.openSession();UserMainMapper userMainMapper = session.getMapper(UserMainMapper.class);User user = userMainMapper .queryUserMainById(1);
4. Example
It is easy to get confused by just reading but not practicing. Look at the examples and go back to read the document, perhaps the effect will be better.
Prepare jar package:
mybatis-3.2.2.jar(mybatis)
mysql-connector-java-5.1.21.jar (database driver)
junit-4.4.jar (test, don't want to use this junit, you can use the main method to test it)
Project structure:
database:
CREATE TABLE `t_user_main` (`f_id` int(11) NOT NULL,`f_username` varchar(20) DEFAULT NULL,`f_age` int(3) DEFAULT NULL,PRIMARY KEY (`f_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;INSERT INTO t_user_main VALUES(1,'testMyBatis',25);
Mybatis' xml configuration --mybatis-config.xml:
<!--?xml version="1.0" encoding="UTF-8" ?--><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://192.168.200.12:3306/test_mybatis"><property name="username" value="root"><property name="password" value="root123"></property></property></property></datasource></transactionmanager></environment></environments><mappers><!-- Register the UserMainMapper.xml file. UserMainMapper.xml is located in the package com.lanhuigu.mybatis.map, so the resource is written as com/lanhuigu/mybatis/map/UserMainMapper.xml--><mapper resource="com/lanhuigu/mybatis/map/UserMainMapper.xml"></mapper></mappers></configuration>
User.java:
package com.lanhuigu.mybatis.entity;import java.io.Serializable;public class User implements Serializable{private static final long serialVersionUID = -3412068097348759984L;private Integer id;private String username;private Integer age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}UserMainMapper.xml:
<!--?xml version="1.0" encoding="UTF-8" ?--> <!-- Specify a unique namespace for this mapper. The value of the namespace is conventionally set to the package name + remove the file name of the suffix of the sql map file. This can ensure that the value of the namespace is unique. For example, namespace="com.lanhuigu.mybatis.map.UserMainMapper" is com.lanhuigu.mybatis.map (package name) + UserMainMapper (UserMainMapper.xml file is removed)--><mapper namespace="com.lanhuigu.mybatis.map.UserMainMapper"> <!-- Write a query SQL statement in the select tag, set the id attribute of the select tag to queryUserMainById, the id attribute value must be unique, and the parameterType attribute cannot be reused to indicate the parameter type used in the query. The resultType attribute indicates the result set type returned by the query resultType="com.lanhuigu.mybatis.entity.User" means encapsulating the query result into an object of the User class Return to the User class, which is the entity class corresponding to the users table--><select id="queryUserMainById" parametertype="int" resulttype="com.lanhuigu.mybatis.entity.User"> select f_id id, f_username username, f_age age from t_user_main where f_id = #{id} </select> </mapper>MyBatisTest.java test code:
package com.lanhuigu.mybatis;import java.io.IOException;import java.io.InputStream;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 com.lanhuigu.mybatis.entity.User;public class MyBatisTest {@Testpublic void testMyBatis() throws IOException {SqlSessionFactory sqlSessionFactory = null;// XML build SqlSessionFactory factory instance SqlSession session = null;// Get the SqlSession object try {//1.mybatis configuration file path, which is placed under classpath, which is equivalent to String resource = "mybatis-config.xml";//2. Read the mybatis configuration file and create the SqlSessionFactory factory instance//======2.1 Use the class loader to load the mybatis configuration file (it also loads the associated mapping file)//InputStream is = MyBatisTest.class.getClassLoader().getResourceAsStream(resource);//Build the SqlSessionFactory factory//sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//======2.2 Use the Resources class provided by MyBatis to load mybatis' configuration file (it also loads the associated mapping file) //Reader reader = Resources.getResourceAsReader(resource); //Build the SqlSessionFactory factory//sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//=====2.3 Use the Resources class provided by MyBatis to load mybatis' configuration file InputStream is = Resources.getResourceAsStream(resource);//Build the SqlSessionFactory factory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//3. Create a sqlSessionsession that can execute sql in the mapping file = sqlSessionFactory.openSession();/*** The identification string for mapping sql: * com.lanhuigu.mybatis.map.UserMainMapper is the value of the namespace attribute of the mapper tag in the UserMainMapper.xml file, * queryUserMainById is the id attribute value of the select tag of the UserMainMapper.xml file. Through the id attribute value of the select tag, * The SQL to be executed can be found through the combination of these two. */// Execute the query and return a unique user object. Note: "com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById" is the identification string that maps SQL. User user = session.selectOne("com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById", 1);System.out.println(user.getUsername());} finally {session.close();}}}Console output:
For the above example, in the test code:
User user = session.selectOne("com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById", 1);System.out.println(user.getUsername());Is this code very unpleasant to use? We have said there is a more direct way:
Add a mapping interface to the project structure map:
package com.lanhuigu.mybatis.map;import com.lanhuigu.mybatis.entity.User;public interface UserMainMapper {public User queryUserMainById(int id);}At the same time, modify the test code as follows:
package com.lanhuigu.mybatis;import java.io.IOException;import java.io.InputStream;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 com.lanhuigu.mybatis.entity.User;import com.lanhuigu.mybatis.map.UserMainMapper;public class MyBatisTest {@Testpublic void testMyBatis() throws IOException {SqlSessionFactory sqlSessionFactory = null;// XML build SqlSessionFactory factory instance SqlSession session = null;// Get the SqlSession object try {//1.mybatis configuration file path, which is placed under classpath, which is equivalent to String resource = "mybatis-config.xml";//2. Read the mybatis configuration file and create the SqlSessionFactory factory instance//======2.1 Use the class loader to load the mybatis configuration file (it also loads the associated mapping file)//InputStream is = MyBatisTest.class.getClassLoader().getResourceAsStream(resource);//Build the SqlSessionFactory factory//sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//======2.2 Use the Resources class provided by MyBatis to load mybatis' configuration file (it also loads the associated mapping file) //Reader reader = Resources.getResourceAsReader(resource); //Build the SqlSessionFactory factory//sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//=====2.3 Use the Resources class provided by MyBatis to load mybatis' configuration file InputStream is = Resources.getResourceAsStream(resource);//Build the SqlSessionFactory factory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//3. Create a sqlSessionsession that can execute sql in the mapping file = sqlSessionFactory.openSession();/*** The identification string for mapping sql: * com.lanhuigu.mybatis.map.UserMainMapper is the value of the namespace attribute of the mapper tag in the UserMainMapper.xml file, * queryUserMainById is the id attribute value of the select tag of the UserMainMapper.xml file. Through the id attribute value of the select tag, * The SQL to be executed can be found through the combination of these two. */// Execute the query and return a unique user object. Note: "com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById" is the identification string that maps SQL/*User user = session.selectOne("com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById", 1);System.out.println(user.getUsername());*/UserMainMapper userMainMapper = session.getMapper(UserMainMapper.class);User user = userMainMapper.queryUserMainById(1);System.out.println(user.getUsername());} finally {session.close();}}} Modify the previous query part to:
UserMainMapper userMainMapper = session.getMapper(UserMainMapper.class);User user = userMainMapper.queryUserMainById(1);
Use an interface that can reasonably describe parameters and return values for a given statement (for example, UserMainMapper.class),
Not only can you execute clearer and type-safe code now, but you don't have to worry about error-prone string literals and casts.
Run the test code and the effect is the same.
UserMainMapper interface location:
Since we have added the interface, mybatis-config.xml can change the configuration for the mapper part and directly map the package file where the UserMainMapper interface is located:
That is to
Modify to
The complete configuration is as follows, and you can verify it by running the test code. This practice is easier to maintain and manage maps in a unified manner:
<!--?xml version="1.0" encoding="UTF-8" ?--><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://192.168.200.12:3306/test_mybatis"><property name="username" value="root"><property name="password" value="root123"></property></property></property></datasource></transactionmanager></environment></environments><mappers><!-- Register the UserMainMapper.xml file. UserMainMapper.xml is located in the package com.lanhuigu.mybatis.map, so the resource is written as com/lanhuigu/mybatis/map/UserMainMapper.xml--><!-- <mapper resource="com/lanhuigu/mybatis/map/UserMainMapper.xml"></mapper> --><package name="com.lanhuigu.mybatis.map"></package></mappers></configuration>
As above, we can see that no matter how we play, is SQL still mapped in UserMainMapper.xml?
Is this implementation unique? Do I have to use xml?
Of course not. If your code above is modified and tested successfully, then let's make the last modification.
Instead of using UserMainMapper.xml to implement mapping, we use Java annotations to implement mapping.
The main modification is the UserMainMapper.java interface, adding a new method queryUserMainByIdNew, and using annotations to implement mapping
mybatis self-resolving interface mapping.
Modified UserMainMapper.java interface:
package com.lanhuigu.mybatis.map;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;import com.lanhuigu.mybatis.entity.User;public interface UserMainMapper {/*** xml*/public User queryUserMainById(int id);/*** java annotation*/@Select("select f_id id,f_username username,f_age age from t_user_main where f_id = ${id} ")public User queryUserMainByIdNew(@Param("id") int id);} The modified test code, run it in the following ways:
package com.lanhuigu.mybatis;import java.io.IOException;import java.io.InputStream;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 com.lanhuigu.mybatis.entity.User;import com.lanhuigu.mybatis.map.UserMainMapper;public class MyBatisTest {@Testpublic void testMyBatis() throws IOException {SqlSessionFactory sqlSessionFactory = null;// XML build SqlSessionFactory factory instance SqlSession session = null;// Get the SqlSession object try {//1.mybatis configuration file path, which is placed under classpath, which is equivalent to String resource = "mybatis-config.xml";//2. Read the mybatis configuration file and create the SqlSessionFactory factory instance//======2.1 Use the class loader to load the mybatis configuration file (it also loads the associated mapping file)//InputStream is = MyBatisTest.class.getClassLoader().getResourceAsStream(resource);//Build the SqlSessionFactory factory//sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//======2.2 Use the Resources class provided by MyBatis to load mybatis' configuration file (it also loads the associated mapping file) //Reader reader = Resources.getResourceAsReader(resource); //Build the SqlSessionFactory factory//sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//=====2.3 Use the Resources class provided by MyBatis to load mybatis' configuration file InputStream is = Resources.getResourceAsStream(resource);//Build the SqlSessionFactory factory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//3. Create a sqlSessionsession that can execute sql in the mapping file = sqlSessionFactory.openSession();/*** The identification string for mapping sql: * com.lanhuigu.mybatis.map.UserMainMapper is the value of the namespace attribute of the mapper tag in the UserMainMapper.xml file, * queryUserMainById is the id attribute value of the select tag of the UserMainMapper.xml file. Through the id attribute value of the select tag, * The SQL to be executed can be found through the combination of these two. */// Execute the query and return a unique user object. Note: "com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById" is the identification string that maps SQL/*User user = session.selectOne("com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById", 1);System.out.println(user.getUsername());*//*UserMainMapper userMainMapper = session.getMapper(UserMainMapper.class);User user = userMainMapper.queryUserMainById(1);System.out.println(user.getUsername());*/UserMainMapper userMainMapper = session.getMapper(UserMainMapper.class);User user = userMainMapper.queryUserMainByIdNew(1);System.out.println(user.getUsername());} finally {session.close();}}}The above is the complete collection of MyBatis introduction (2) introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!