1. Introduction to mybatis
1.1 analysis of original Jdbc operation
The problems existing in the original development are as follows:
1. The frequent creation and release of database connections cause a waste of system resources, which affects the system performance.
2. sql statements are hard coded in the code, which makes the code difficult to maintain. The actual application of sql may change greatly. sql changes need to change the java code.
3. When querying, you need to manually encapsulate the data in the result set into the entity. When inserting, you need to manually set the data of the entity to the placeholder position of the sql statement.
Solution:
1. Initialize the connection resource using the database connection pool.
2. Extract sql statements into xml configuration files.
3. The underlying technologies such as reflection and introspection are used to automatically map the attributes and fields of entities and tables.
1.2 what is Mybatis
The excellent persistence layer framework based on java encapsulates jdbc internally, so that developers only need to pay attention to the sql statement itself, and do not need to spend energy to deal with the complicated processes such as loading driver, creating connection and creating statement.
mybatis configures various statements to be executed by means of xml or annotation, and maps the final executed sql statements through java objects and sql dynamic parameters in the statement.
Finally, the mybatis framework executes sql and maps the results to java objects and returns them. ORM (object relational mapping) is adopted to solve the problem of entity and database mapping. jdbc is encapsulated and the underlying access details of jdbc api are shielded, so that we can complete the persistence operation of database without dealing with jdbc api.
2. Mybatis quick start
2.1 Mybatis development steps
1. Add coordinates of Mybatis
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
2. Create data table
3. Write the entity class corresponding to the data table
4. Write mapping file xml
<?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="userMapper"> <select id="findAll" resultType="com.xc.domain.User"> select * from user </select> </mapper>
The mapping header is fixed through namespace ID to determine a specific sql statement, and resultType is configured as the corresponding result set entity class.
5. Write the core file sqlmapcongfig xml
<?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> <!-- Data source environment--> <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://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!-- Load mapping file --> <mappers> <mapper resource="com\xc\mapper\UserMapper.xml"/> </mappers> </configuration>
The header of the core file is fixed. The data source environment can be configured in it, and multiple environments can be configured. Declaut is the default environment,
It can be configured with transaction processor, database type and so on. The core file loads the mapping file, which corresponds to the sql statement.
6. Write test class
@Test public void test1() throws IOException { //Get core profile InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); //Get Session factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); //Get Session session object SqlSession sqlSession = sqlSessionFactory.openSession(); //The execution operation parameter is List<Object> userList = sqlSession.selectList("userMapper.findAll"); System.out.println(userList); sqlSession.close(); }
The idea is to obtain the core configuration file, then obtain the session object, execute sql statements through the session object, then return the results, and finally close the session.
3. Overview of mybatis mapping file
4. Addition, deletion, modification and query of mybatis
4.1 insert data operation of mybatis
<!-- Insert label--> <insert id="save" parameterType="com.xc.domain.User"> insert into user values(#{id},#{username},#{password}) </insert>
@Test public void test2() throws IOException { //Create an insert data User user = new User(); user.setUsername("tom"); user.setPassword("123"); //Get core profile InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); //Get Session factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); //Get Session session object SqlSession sqlSession = sqlSessionFactory.openSession(); //Perform operations sqlSession.insert("userMapper.save",user); //Mybatis needs to commit the transaction to perform the update operation sqlSession.commit(); sqlSession.close(); }
Precautions for insertion:
Insert statements use the insert tag
Use the parameterType attribute in the mapping file to specify the type of data to insert
Use #{entity attribute name} in Sql statement to refer to attribute value in entity
The API used for the insert operation is sqlseesion Insert ("namespace. id", entity object)
The insert operation involves database changes, so you should use the commit transaction displayed by the sqlSession object, that is, sqlSession commit()
Data modification of mytis 2.4
Except for the key parts, the rest and insertion operations have little change
<update id="update" parameterType="com.xc.domain.User"> update user set username = #{username},password=#{password} where id=#{id} </update>
//Perform operations sqlSession.update("userMapper.update",user);
Note:
Modify the statement using the update tag
The API used for modification is sqlsession Update ("namespace. id", entity object)
Manual submission
4.3 deleting mybatis
<delete id="delete" parameterType="java.lang.Integer"> delete from user where id=#{id} </delete>
//Perform operations sqlSession.delete("userMapper.delete",7);
Note:
Delete statements are labeled with delete
Use #{arbitrary string} to refer to a single parameter passed in a Sql statement
The API used for the delete operation is sqlsession Delete ("namespace. id",Object)
5. Overview of mybatis core configuration file
5.1 hierarchical relationship of mybatis core configuration file
Configuration configuration
properties property
Settings settings
typeAliases type aliases
objectFactory object factory
plugins plug-in
environments environment
Environment environment variable
Transaction manager
dataSource datasource
databaseldProvider database vendor ID
mappers mapper
5.2 common configuration analysis
1. Environment label
The configuration of database environment supports multi environment configuration
Transaction manager: JDBC configuration directly uses the commit and rollback settings of JDBC. It relies on the connection from the data source to manage the transaction scope.
There are three types of data eyes:
UNPOOLED: the implementation of the data source only opens and closes the connection every time it is requested.
POOLED: the implementation of this data source uses the concept of "pool" to organize JDBC connection objects.
JNDI: not involved for the time being.
2.mapper label
This tag is used to load mapping. The loading methods are as follows:
Resource references using relative paths, such as < mapper resource = "XX / XX / XX / XX. XML" / >, are written from the resource directory. This is the most commonly used method.
Use a fully qualified resource locator (URL).
Use the mapper interface to implement the fully qualified class name of the class.
Register all the mapper interface implementations in the package as mappers.
3.Properties tab
In actual development, it is customary to extract the configuration information of the database separately into a properties file, which can load additional configured properties files
4.typeAliases label
The mybatis framework has set the aliases of some common types for us. You can directly rewrite the package name and class name into aliases in parameterType.
For example, string can be written as string
Long is written as long
Integer is written as int
Double is written as double
boolean is written as boolean
In addition to some aliases already set by the framework, we can also choose to customize some aliases.
<typeAliases> <typeAlias type="com.xc.domain.User" alias="user"/> </typeAliases>
It should be noted that the tag segment of the user-defined alias has location requirements and needs to be placed before the environment tag, otherwise a mismatch error will be reported.
After setting the alias, the parameter type can be directly replaced by the alias in the mapping configuration file.
<update id="update" parameterType="user"> update user set username = #{username},password=#{password} where id=#{id} </update>
6.MyBatis corresponding API
//Get core profile InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); //Get Session factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); //Get Session session object SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession is a very powerful class in MyBatis. Its main methods are:
selectOne: query a
selectList: query collection
int insert: Insert
int update: update
int delete: delete
The main ways to operate transactions are:
void commit() commit transaction
void rollback() rolls back the transaction