Quick start or review of Mybatis knowledge points

foreword

This article records the quick start and basic knowledge points of mybatis, which is convenient for knowledge review, and the deficiencies will be continuously added in the future. Thank you for reading!

Introduction to Mybatsi

Apache's open source project iBatis

It is a Java-based persistence layer framework that simplifies large chunks of native JDBC code

Lightweight, great performance

  • SQL and Java coding are separated, and the functional boundaries are clear. Java codes focus on business, SQL statements focus on data
  • The development efficiency is slightly lower than that of HIbernate, but it is completely acceptable

MyBatis Features

  1. MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping
  2. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets
  3. MyBatis can use simple XML or annotations for configuration and original mapping, and map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) into records in the database
  4. MyBatis is a semi-automatic ORM (Object Relation Mapping) framework

Quick start of Mybatis

1. Import the core dependencies of Mybatis

	<!-- Mybatis核心 -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.5.7</version>
	</dependency>

2. Create the core configuration file of MyBatis

In the case of maven, create its core configuration file under the resource folder
insert image description here

<?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>  
	<!--设置连接数据库的环境-->  
	<environments default="development">  
		<environment id="development">  
			<transactionManager type="JDBC"/>  
			<dataSource type="POOLED">  
				<property name="driver" value="com.mysql.cj.jdbc.Driver"/>  
				<property name="url" value="jdbc:mysql://localhost:3306/MyBatis"/>  
				<property name="username" value="root"/>  
				<property name="password" value="123456"/>  
			</dataSource>  
		</environment>  
	</environments>  
	<!--引入映射文件-->  
	<mappers>  
		<mapper resource="mappers/UserMapper.xml"/>  
	</mappers>  
</configuration>

If it is by Spring, it is managed by Spring. What kind of connection pool and data source are written in the yml configuration file.


3. Create entity classes under the pojo package according to the table fields in the database

A pojo example corresponds to a table

insert image description here
There is no need to say more about the entity class of POJO


4. Create a mapper package as a persistence layer

Create the corresponding mapper interface according to the pojo entity class.
For example, the entity class is User, which is UserMapper

public interface UserMapper {
    
      
	/**  
	* 添加用户信息  
	*/  
	int insertUser();  
}

An insert method is added as a new operation method


5. Create a mapper mapping file under resource/mappers


One-to-one correspondence between table-entity class-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="com.atguigu.mybatis.mapper.UserMapper">  
	<!--int insertUser();-->  
	<insert id="insertUser">  
		insert into t_user values(null,'张三','123',23,'女')  
	</insert>  
</mapper>

The following are two consistentmore important

insert image description here

6. Introduce the xml mapping file in the core configuration

insert image description here


7. Call the interface and test the function

Although the business code for the new data is written here, no one adjusts it . It is not the same as in the project. There is a business layer and then calls it, so here I write a junit test to call the mapper method to operate the database.

public class UserMapperTest {
    
    
    @Test
    public void testInsertUser() throws IOException {
    
    
        //读取MyBatis的核心配置文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        //获取SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        //获取sqlSession,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
        //SqlSession sqlSession = sqlSessionFactory.openSession();
	    //创建SqlSession对象,此时通过SqlSession对象所操作的sql都会自动提交  
		SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //通过代理模式创建UserMapper接口的代理实现类对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
        int result = userMapper.insertUser();
        //提交事务
        //sqlSession.commit();
        System.out.println("result:" + result);
    }
}

At this point, a basic demo of mybatis is completed, and the function of adding new data is realized. When the mapper interface is called, it will be mapped to mapper.xml, and the sql statement will be executed in xml.


8. Automatic submission of transactions

insert image description here

insert image description here


Other crud operations are basically similar. Create an operation method, whether to modify or delete, etc., and then write the corresponding SQL statement in the mapping xml of the mapper. The statement id is bound to the method name, so that when the method is called, it is known which one is executed SQL


Knowledge review of Mybatis

Addition, deletion, modification and query of MyBatis

They are all simple sql written in crud in xml, there is nothing to say

  1. Add to

    <!--int insertUser();-->
    <insert id="insertUser">
    	insert into t_user values(null,'admin','123456',23,'男','[email protected]')
    </insert>
    
  2. delete

    <!--int deleteUser();-->
     <delete id="deleteUser">
         delete from t_user where id = 6
     </delete>
    
  3. Revise

    <!--int updateUser();-->
     <update id="updateUser">
         update t_user set username = '张三' where id = 5
     </update>
    
  4. Query an entity class object

    <!--User getUserById();-->  
    <select id="getUserById" resultType="com.atguigu.mybatis.bean.User">  
    	select * from t_user where id = 2  
    </select>
    
  5. query collection

    <!--List<User> getUserList();-->
    <select id="getUserList" resultType="com.atguigu.mybatis.bean.User">
    	select * from t_user
    </select>
    

But for the return value reception of the query, there are some changes

  1. The label select of the query must set the attribute resultType or resultMap, used to set the mapping relationship between entity classes and database tables
    • resultType: automatic mapping, used when the attribute name is consistent with the field name in the table
    • resultMap: custom mapping, used for one-to-many or many-to-one or inconsistent field names and attribute names

  1. When the queried data is multiple, you cannot use the entity class as the return value, you can only use the collection, otherwise the exception TooManyResultsException will be thrown; but if there is only one queried data, you can use the entity class or collection as the return value
    insert image description here

Introduce properties in the core configuration file

insert image description here

Replaced by setting the database connection configuration information in properties

insert image description here

After setting, you need to import the set properties file into the core configuration file of mybatis

insert image description here

The original read configuration information is replaced by the following ${ } method to read

insert image description here


Set an alias for resultType

Here the resultType receiving type is very tiring to write the full path class name all the time. To make it easier, give the full path class name a simple alias, so that even if there are too many SQL queries, it will not be so tiring.

Set up an alias first
insert image description here


Look at the effect again

insert image description here


The second way is more commonly used

insert image description here

Use the package tag to set all the classes under the pojo package to the default alias (if you don’t write the alias, set it to the default), which is the class name itself, so that all the classes under the package are set up, so that I don’t need to set them one by one. much easier

Set the default type alias for all types under the package in units of packages

The core configuration file can also be imported into the mapping file as above, and imported in batches

When creating this package, the middle is separated by / instead of .
insert image description here
( the above is not .xml but .mapper by mistake, the interface and the mapped package name must be consistent ), so that it can be imported in batches in units of packages


Make templates for xml files

It is a waste of time to do these steps for the mybatis settings of each demo. If it is created as a template, it will be initialized as soon as it is created. Isn’t it beautiful?

The template of mybatis-config.xml core configuration file

<?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>

<!--    引入jdbc配置文件信息-->
    <properties resource="jdbc.properties"/>
<!--    配置别名-->
    <typeAliases>
<!--        给实体类设置别名-->
        <package name=""/>
    </typeAliases>
    <!--设置连接数据库的环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
<!--        以包为单位,将包中的xml文件全部引入-->
        <package name="com.mapper"/>
    </mappers>
</configuration>

Copy these codes, and then
open it in the setting as follows

insert image description here

Add a mybatis-config template here

insert image description here


In this way, we can also make a mapper template, so that we don’t have to write the large section in front of the mapper.
For the code of the mapper, the above operation is also set as a template.

insert image description here

<?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="">

</mapper>

Two ways for MyBatis to get parameter values ​​(emphasis)

Guess you like

Origin blog.csdn.net/giveupgivedown/article/details/129817314