This article has been exclusively authorized to be used by [Xinhua front and back development]. Use other platforms after contacting the author
[TOC]
brief introduction
JDBC, Hibernate and Mybatis are the most commonly used databases. By connecting to the database through JDBC, we will find that the workload is quite complex. We have to deal with some trivial closures. Then we have to manage our own participation. Based on this, the ORM(Object Relational Mapping) model is generated.
#ORM model
- Simply put, ORM model is the mapping model of database tables and Java objects. It mainly solves the mapping between database and Java object. We can manipulate entity objects to manipulate database tables. The advantage is that we don't need to know much about the database. It reduces the cost of our study.
Hibernate
- Based on ORM model, our second protagonist will appear soon. However, due to the complexity of Hibernate configuration and poor operation performance. Although it greatly weakened our sql, it was quickly eliminated because of its poor performance.
Ibatis
-
In strict sense, the predecessor of Mybatis should be Ibatis, later we call it Mybatis. In order to solve the problem of Hibernate, Mybatis has produced a full table mapping framework relative to Hibernate, which can be said to be a semi-automatic mapping framework. Because it is a framework of entity and sql.
-
Mybatis has three main objects: sql, entity and mapping rules. Compared with hibernate, there is more sql writing, but it is precisely because of the sql writing that mybatis becomes very convenient. Hibernate can't call these database methods of stored procedures because it doesn't use sql. But mybatis is different. Mybatis can call stored procedures in sql.
Environment building
jar
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.0</version> </dependency>
To configure
- In the above figure, we can find that the annotation or interface provided in Mybatis is used to operate the database. So here we have an interface. The interface corresponds to an xml file. Both make up a component of Mybatis.
package com.github.zxhtom.mapper; import com.github.zxhtom.model.Student; import java.util.List; public interface StudentMapper { /** * Get student list * @return */ public List<Student> getStudents(); /** * Get student information through id * @param id * @return */ public Student getStudentByStuId(String id); }
- The interface corresponds to xml, which records real sql. Note here that the location of xml should be in the same name as the entity in the agreed folder
<?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" > <mapper namespace="com.github.zxhtom.mapper.StudentMapper"> <select id="getStudents" resultType="com.github.zxhtom.model.Student"> select * from student </select> <select id="getStudentByStuId" resultType="com.github.zxhtom.model.Student"> select * from student where id=#{id} </select> </mapper>
xml mode configuration
- With the above interface and xml, let's start to configure our Mybatis environment.
<?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> <!--Import external profile--> <properties resource="config.properties"></properties> <!--Define aliases--> <typeAliases> <package name=""/> </typeAliases> <!--Define database information, use by default development Database construction environment--> <environments default="development"> <environment id="development"> <!--jdbc Affairs Management--> <transactionManager type="JDBC"></transactionManager> <!--Configure database connection information--> <dataSource type="POOLED"> <property name="driver" value="${database.driver}"/> <property name="url" value="${database.url}"/> <property name="username" value="${database.username}"/> <property name="password" value="${database.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/github/zxhtom/mapper/StudentMapper.xml"></mapper> </mappers> </configuration>
- Then we can load the xml environment configuration and build our sqlsession
//Get the location of mybatis-config.xml InputStream inputStream = Resources.getResourceAsStream(Constant.MYBATIS); //Load mybatis config and create sqlsessionfactory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //Create sqlsession object SqlSession sqlSession = sqlSessionFactory.openSession(); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("id", 1); //Execute select statement, map resultSet to object and return StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); List<Student> students = studentMapper.getStudents(); studentPrint(students);
Code mode configuration
- Another way to configure the environment is provided by the official Java object. This configuration is more delicate, but the problem is that some of our configurations will be hard coded in the code. Here we move the hard coded things out through the Properties file.
Map<Object, Object> properties = PropertiesUtil.getProperties("config.properties"); PooledDataSource dataSource = new PooledDataSource(); dataSource.setDriver(properties.get("database.driver").toString()); dataSource.setUrl(properties.get("database.url").toString()); dataSource.setUsername(properties.get("database.username").toString()); dataSource.setPassword(properties.get("database.password").toString()); //How to build database TransactionFactory transactionFactory = new JdbcTransactionFactory(); //Create database running environment Environment environment = new Environment("development",transactionFactory,dataSource); //Building the Configure object Configuration configuration = new Configuration(environment); //Registration alias configuration.getTypeAliasRegistry().registerAlias("stu", Student.class); //Add a mapper configuration.addMapper(StudentMapper.class); //Using sqlsessionfactoryBuilder to build sqlsessionfactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); SqlSession sqlSession = sqlSessionFactory.openSession(); StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); List<Student> students = studentMapper.getStudents(); studentPrint(students);
Comparison of two ways
-
I stressed above that our StudentMapper.xml and StudentMapper.java should have the same name and be in the same location. Why is that. Because in the Mybatis source code, the XML file with the same name under the same directory as the Java object will be read by default as the sql configuration file.
-
But in the later stage, Java and XML will be expanded more and more, which will be very messy together. As a framework, it is not so limited. In the XML configuration environment, we inject Mapper.xml through mappers -- > mapper tag. The XML path here is not required to be in the same directory. We can change it at will here. The above limitations are in the way java code builds the environment. Because in Java code mode, we only register the mapper interface through Java objects. In this way, XML with the same name under the same directory will be loaded by default
Mybatis structure
-
The process of learning is the process of cognition. Next let's get to know the core components of Mybnatis.
-
SqlSessionFactoryBuilder: generate SqlSessionFactory according to XML (mybatis config. XML) or Java code (code mode)
-
SqlSessionFactory: building SqlSession
-
SqlSession: you can send sql execution and return results, or get Mapper interface
-
sql mapper: a unique component of mybatis. There are Java interfaces and xml files as a whole. Responsible for parsing the sql in xml and passing it to the database to get the result
Source code interpretation xml environment loading
- Because of the category of basic courses, here the source of the trace point to the end (no matter how deep I will not).
- The focus is on parsing the mybatis-config.xml tag. This section will introduce the analysis and function of each tag. Leave a message or click like to let us see your love for this piece. If you leave a message with more likes, it will be published as soon as possible.
Mapper interpretation
- As mentioned above, mapper is a Mybatis component composed of Java+xml. The above case also shows the preparation of the two. Java is actually an interface defined method. Just put our sql on the corresponding tag in xml.
- In the circled sql, we will find that it is different from our usual sql. #{id} is the input parameter provided by Mybatis. The real sql will be populated when it is submitted to the database. Here's another thing to note: we wrote select *. Because the database fields are the same as our entity properties. So Mybatis will automatically map the same field content to the entity. This enables automatic mapping.
- Compared with Hibernate, mybatis is semi-automatic. If our entity is different from the database field (note that hump and hump can be considered the same in the database by setting. Mybatis also provides functions that can be mapped. Here we think it is the same). We can map database fields and entity fields through resultMap. This is what we call semi-automatic mapping
Ibatis
- Although we use Mybatis. But Ibatis's previous methods are still preserved. Mention it here. But it is not recommended to execute sql in a way