06_ 01_ Basic application of mybatis

Mybatis task 1: basic application

Main contents of course tasks:

  • Framework introduction
  • Mybatis:
  • ORM
  • quick get start
  • Brief overview of mapping files
  • Implement CRUD
  • Introduction to core configuration file
  • api introduction
  • Development and use of dao layer of mybatis (interface proxy mode)

SSM = springmvc + spring + mybatis

I. Introduction to the framework

1.1 three tier architecture

The commonly used architecture for software development is a three-tier architecture, which is popular because of the clear division of tasks. It generally includes the following three layers:

  • Persistence layer: it mainly completes the operations related to the database, that is, the addition, deletion, modification and query of the database.
    Because the object accessed by the database is generally called Data Access Object (DAO), some people call the persistence layer Dao layer.
  • Business layer: it mainly defines and implements business logic according to functional requirements.
    Because it mainly provides services for the upper layer, some people call the Business layer Service layer or Business layer.
  • Presentation layer: it mainly completes the interaction with the end user of the software, and requires an interactive interface (UI).
    Therefore, some people call the presentation layer web layer or View layer.
    The calling relationship between the three-tier architecture is: the presentation layer calls the business layer, and the business layer calls the persistence layer.
    Data interaction is inevitable between layers. We generally use java entity objects to transfer data.

1.2 framework

1.2.1 what is a framework?

A framework is a set of specifications. Since it is a specification, you must abide by the constraints specified in the framework when using the framework.
The framework can be understood as semi-finished software. After the framework is completed, it will be developed on its basis.

1.2.2 why use framework?

The framework encapsulates some redundant and low reuse code for us. Using reflection and dynamic proxy mechanism, the code is realized
Usability allows developers to focus on the core business code implementation.
For example, when developing with a servlet, you need to get the parameters of the form in the servlet. It's very troublesome to get them every time, and the framework is at the bottom
The reflection mechanism and interceptor mechanism are used to help us obtain the value of the form. We must use jdbc every time we do some simple crud
Write sql, but it doesn't need to be so troublesome to use the framework. You can call the method directly. Of course, since you are using a framework, you still need to
Follow some of its specifications for configuration

1.2.3 common frames

There are many frameworks in the Java world. Each framework exists to solve some or some problems. Listed below
In former enterprises
Several popular frameworks (be sure to note which layer they are used to solve):
Persistence layer framework: a framework focusing on data persistence. Commonly used are mybatis, hibernate, spring jdbc and so on.
Presentation layer framework: a framework that focuses on solving user interaction. The common ones are struts 2, spring mvc and so on.
Full stack framework: a framework that can provide solutions at all layers. spring is more famous.
With so many frameworks, how can we choose?
We learn Spring + Spring MVC + mybatis (SSM) based on the most commonly used combination in the enterprise

II. Introduction to Mybatis

1.1 original jdbc operation (query data)

1.2 analysis of original jdbc operation

The problems existing in the original jdbc development are as follows:
① The frequent creation and release of database connections cause a waste of system resources, which affects the system performance
② 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.
③ When querying, you need to manually encapsulate the data in the result set into the entity.
Solutions to the above problems:
① Initialize connection resources using database connection pool
② Extract sql statements into xml configuration files
③ Use reflection, introspection and other underlying technologies to automatically map attributes and fields between entities and tables

1.3 introduction to mybatis

MyBatis is an excellent semi-automatic lightweight persistence layer framework based on ORM. It encapsulates the process of jdbc operating the database, so that developers only need to pay attention to SQL itself, and do not need to spend energy to deal with complicated jdbc process codes such as registering drivers, creating connection s, creating statement s, manually setting parameters, result set retrieval and so on

mybatis history

MyBatis was originally an open source project of apache, iBatis. In June 2010, the project was migrated from apache software foundation to Google Code. With the development team switching to Google Code, iBatis was officially renamed MyBatis, and the code was migrated to Github in November 2013
Github address: https://github.com/mybatis/mybatis-3/

1.4 ORM idea

ORM (Object Relational Mapping) Object Relational Mapping

  • O (object model):
    Entity objects, that is, the entity JavaBeans established in the program according to the database table structure
  • R (data structure of relational database):
    Relational in the relational database domain (established database tables)
  • M (mapping):
    The mapping from R (database) to O (object model) can be mapped through XML file
  • realization:
    (1) One to one correspondence between entity classes and database tables
    First, make the entity class correspond to the database table
    Then let the entity class attributes correspond to the fields in the table
    (2) You do not need to directly operate the database table, but directly operate the entity class object corresponding to the table

    ORM as an idea
    Help us track the changes of entities, translate the changes of entities into sql scripts and execute them in the database, that is, map the changes of entities to the changes of tables.
    mybatis uses the ORM idea to solve the problem of entity and database mapping, encapsulates jdbc and shields the underlying access details of jdbc api, so that we can complete the persistence operation of database without dealing with jdbc api

III. Mybatis quick start

3.1 MyBatis development steps

MyBatis official website address: http://www.mybatis.org/mybatis-3/

Case requirements: query all records in the user table of the database through mybatis, package them into the user object, and print them on the console
Step analysis:

1.Create database and user surface

2.establish maven Project, import dependency( MySQL Drive mybatis,junit)

3.to write User Entity class

4.to write UserMapper.xml Mapping profile( ORM Thoughts)

5.to write SqlMapConfig.xml Core profile database environment configuration
 Introduction of mapping relationship configuration(Path to import mapping profile)

6.Write test code
	// 1. Load the core configuration file
	// 2. Get sqlSessionFactory factory object
	// 3. Get sqlSession session object
	// 4. Execute sql
	// 5. Print results
	// 6. Release resources

3.2 code implementation

  1. Create user data table
CREATE DATABASE `mybatis_db`; USE `mybatis_db`;

CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT 'User name',
`birthday` datetime default NULL COMMENT 'birthday',
`sex` char(1) default NULL COMMENT 'Gender',
`address` varchar(256) default NULL COMMENT 'address',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- insert....
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'son
 Admire','2020-11-11 00:00:00','male','Haidian, Beijing'),(2,'Ying Dian','2020-12-12 00:00:00','male','north
 Jinghaidian');
  1. Import the coordinates of MyBatis and other related coordinates
<!--Specify encoding and version-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>1.11</java.version>
        <maven.compiler.source>1.11</maven.compiler.source>
        <maven.compiler.target>1.11</maven.compiler.target>
    </properties>
    <!--  Introduce related dependencies  -->
    <dependencies>
    <!--  introduce mybatis rely on-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>

        <!--  introduce mysql drive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.17</version>
        </dependency>

        <!--  introduce junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. Write User entity
public class User { 
	private Integer id;
	private String username; 
	private Date birthday; 
	private String sex; 
	private String address;
	// getter/setter omitted
}
  1. Write UserMapper mapping file
<?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">
<!--namespace Namespaces: and id Attributes together constitute a unique identifier namespace:id = user.findAll-->
<mapper namespace="userMapper">
    <!--Query all
        resultType:Return result type (auto map encapsulation),The full path of the entity to encapsulate
    -->
    <select id="findAll" resultType="com.lagou.domain.User">
        select * from user
    </select>
</mapper>
  1. Write MyBatis core document
<?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> <!--Environment configuration-->
    <environments default="mysql"> <!--use MySQL environment-->
        <environment id="mysql"> <!--use JDBC Type transaction manager-->
            <transactionManager type="JDBC"></transactionManager> <!--Use connection pool-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <!-- Chinese garbled code may appear, so add it after it?useUnicode=true&amp;characterEncoding=utf-8  -->
                <property name="url" value="jdbc:mysql:///mybatis_db?useUnicode=true&amp;characterEncoding=utf-8"></property>
                <property name="username" value="root"></property>
                <property name="password" value="qwer1234"></property>
            </dataSource>
        </environment>
    </environments> <!--Load mapping configuration-->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>
  1. Writing test classes
package com.lagou.test;

import com.lagou.domain.User;
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.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {

    /*
    * Quick start test method
    * */

    @Test
    public void mybatisQuickStart() throws IOException {
        //1. Load the core configuration file and load the core configuration file as a byte input stream
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");

        //2. Get sqlSessionFactory factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        //3. Obtain the sqlSession session object and operate the database with this object
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4. Parameters passed in from the sql execution object: statementid: namespace, ID
        List<User> users = sqlSession.selectList("userMapper.findAll");

        //5. Traverse the print results
        for (User user : users) {
            System.out.println(user);
        }

        //6. Close resources
        sqlSession.close();
    }


}

3.3 knowledge summary

1. establish mybatis_db Database and user surface 
2. Create project, import dependency 
3. establish User Entity class 
4. Write mapping file UserMapper.xml 
5. Preparation of core documents SqlMapConfig.xml 
6. Writing test classes

IV. overview of Mybatis mapping file

V. addition, deletion and modification of Mybatis

5.1 NEW

  1. Write the mapping file usermapper xml
  <!--    New user-->
    <!-- #{}: placeholder in mybatis, equivalent to?, in JDBC?, The value in {} should be consistent with the value name passed in the entity object
        parameterType: Specifies the type of parameter received-->
    <insert id="saveUser" parameterType="com.lagou.domain.User">
        insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
    </insert>
  1. Writing test classes
   /*Test and increase customers*/
    @Test
    public void testSave() throws IOException {
   		// Load core profile
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        // Get SqlSessionFactory factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        // Get SqlSession session object
        SqlSession sqlSession = sqlSessionFactory.openSession();
		
		// Execute sql
        User user = new User();
        user.setUsername("jack");
        user.setBirthday(new Date());
        user.setSex("male");
        user.setAddress("Beijing Haiding");
        sqlSession.insert("userMapper.saveUser",user);
       // DML statement, manually commit transaction
        sqlSession.commit();
        // Release resources
        sqlSession.close();
    }
  1. New precautions
-Insert statement use insert label

-Use in mapping files parameterType Property specifies the type of data to insert

-Sql Used in statements#The {entity attribute name} refers to the attribute value in the entity

-Used by the insert operation API yes sqlSession.insert("Namespace.id",Entity object);

-The insert operation involves database data changes, so use sqlSession Object to display the commit transaction,
Namely sqlSession.commit()

5.2 modification

  1. Write the mapping file usermapper xml
    <!--    Update user -->
    <update id="updateUser" parameterType="com.lagou.domain.User">
        update user set  username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>
  1. Writing test classes
    /*
    * Test update user
    * */
    @Test
    public void testUpdate() throws IOException {
        // Load core profile
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        // Get SqlSessionFactory factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        // Get SqlSession session object
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // Execute sql
        User user = new User();
        user.setId(4);
        user.setUsername("lucy");
        user.setSex("female");
        user.setBirthday(new Date());
        user.setAddress("Chaoyang, Beijing");
        sqlSession.update("userMapper.updateUser",user);

        // DML statement, manually submit transaction sql
        sqlSession.commit();
        // Release resources
        sqlSession.close();
    }
  1. Notes for modification
-Modify statement usage update label

-Modify the used by the operation API yes sqlSession.update("Namespace.id",Entity object);

5.3 deletion

1. Write the mapping file usermapper xml

<!--delete-->
<delete id="delete" parameterType="java.lang.Integer"> 
delete from user where id = #{id}
</delete>

2. Write test class

/*
     * Test delete user
     * */
    @Test
    public void testDetele() throws IOException {
        // Load core profile
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        // Get SqlSessionFactory factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        // Get SqlSession session object
        SqlSession sqlSession = sqlSessionFactory.openSession();
		//Execute sql
      	sqlSession.delete("userMapper.deleteUser",4);

        // DML statement, manually submit transaction sql
        sqlSession.commit();
        // Release resources
        sqlSession.close();
    }

3. Delete precautions

-Delete statement use delete label

-Sql Used in statements#Single parameter passed by {arbitrary string} reference

-Used by delete operation API yes sqlSession.delete("Namespace.id",Object);

5.4 knowledge summary

*query
 code:
List<User> list = sqlSession.selectList("UserMapper.findAll");
Mapping file:
<select id="findAll" resultType="com.lagou.domain.User"> select * from user
</select>

*newly added
 code:
sqlSession.insert("UserMapper.save", user);
Mapping file:
<insert id="save" parameterType="com.lagou.domain.User"> insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
</insert>

*modify
 code:
sqlSession.update("UserMapper.update", user);
Mapping file:
<update id="update" parameterType="com.lagou.domain.User">
update user set username = #{username},birthday = #{birthday}, sex = #{sex},address = #{address} where id = #{id}
</update>

*delete
 code:
sqlSession.delete("UserMapper.delete", 4);
Mapping file:
<delete id="delete" parameterType="java.lang.Integer"> 
delete from user where id = #{id}
</delete>

Vi. overview of Mybatis core document

6.1MyBatis core profile hierarchy

The MyBatis configuration file contains settings and attribute information that deeply affect MyBatis behavior. The top-level structure of the configuration document is as follows:

6.2 MyBatis common configuration analysis

  1. environments tab
    The configuration of database environment supports multi environment configuration
1.Where, transaction manager( transactionManager)There are two types:
-JDBC: 
This configuration is used directly JDBC Commit and rollback settings, which rely on the connection from the data source to manage the transaction scope.

-MANAGED: 
This configuration does little. It never commits or rolls back a connection, but lets the container manage the entire life cycle of the transaction.
For example: mybatis And spring After integration, the transaction is handed over to spring Container management.

2.Where, data source( dataSource)There are three common types:
-UNPOOLED: 
The implementation of this 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" JDBC Organize connected objects.

-JNDI :
This data source is implemented to enable EJB Or application server. The container can configure data sources centrally or externally, and then place one JNDI Data source reference for context
  1. properties tag
    In actual development, it is customary to extract the configuration information of the data source separately into a properties file, which can load additional configured properties:
    File name: JDBC properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis_db?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=root
jdbc.password=qwer1234

Properties: in sqlmapconfig Add the properties tag in the XML, modify the value of the fixed configuration, and uniformly put the configuration in the configuration file JDBC Properties

  1. typeAliases label
    A type alias is a short name for a Java type.
    In order to simplify the Java type setting of the mapping file, the mybatis framework sets some common type aliases for us:

    The original type name is configured as follows:

    Configure typeAliases as com lagou. domain. User defines the alias as user:
<?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> <!--Environment configuration-->
    <!--    load properties file-->
    <properties resource="jdbc.properties"></properties>

    <!--    Set alias-->
    <typeAliases>
        <!--  Method 1: alias a single entity-->
        <!-- <typeAlias type="com.lagou.domain.User" alias="user"></typeAlias>-->
        <!-- Commonly used: Method 2: batch alias. Alias is the class name and is not case sensitive-->
        <package name="com.lagou.domain" />
    </typeAliases>

    <environments default="mysql"> <!--use MySQL environment-->
        <environment id="mysql"> <!--use JDBC Type transaction manager-->
            <transactionManager type="JDBC"></transactionManager> <!--Use connection pool-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <!-- Chinese garbled code may appear, so add it after it?useUnicode=true&amp;characterEncoding=utf-8  -->
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments> <!--Load mapping configuration-->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>
  1. mappers tag
    The tag is used to load mapping. The loading methods are as follows:
1.Use a resource reference relative to the classpath, for example:
	<mapper resource="org/mybatis/builder/userMapper.xml"/>

2.Use fully qualified resource locators( URL),For example:
	<mapper url="file:///var/mappers/userMapper.xml"/>


<The following two mapper Used in agent development:Temporary understanding
3.Use the mapper interface to implement the fully qualified class name of the class, for example:
	<mapper class="org.mybatis.builder.userMapper"/>

4.Register all mapper interface implementations in the package as mappers, for example:
	<package name="org.mybatis.builder"/>

6.3 knowledge summary

Core profile common configuration:
Properties tag: this tag can load external properties files

<properties resource="jdbc.properties"></properties>

typeAliases label: set type aliases

<typeAlias type="com.lagou.domain.User" alias="user"></typeAlias>

mappers tab: load mapping configuration

<mapper resource="com/lagou/mapper/UserMapping.xml"></mapper>

environments tab: data source environment configuration

<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="${jdbc.username}"/>
			<property name="password" value="${jdbc.password}"/>
		</dataSource>
	</environment>
</environments>

VII. Overview of Mybatis API

7.1 API introduction

7.1 SqlSession factory builder SqlSessionFactoryBuilder

Common API: SqlSessionFactory build(InputStream inputStream)
Build a SqlSessionFactory object by loading the input stream of the core file of mybatis

String resource = "org/mybatis/builder/mybatis-config.xml";
 //Step 1: load resources
InputStream inputStream = Resources.getResourceAsStream(resource);
//Step 2: the builder of sqlSession factory loads the input stream to build sqlSessionFactory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); 
SqlSessionFactory factory = builder.build(inputStream); 
//With the help of sqlSessionFactoryBuilder, the factory constructor creates sqlSession through the openSession() method
SqlSession sqlSession = sqlSessionFactory.openSession();

Among them, the Resources tool class, which is located at org apache. ibatis. IO package.
The Resources class helps you load resource files from the classpath, the file system, or a web URL.

6.2 SqlSession factory object SqlSessionFactory

SqlSessionFactory has multiple methods to create SqlSession instances. There are two commonly used:

6.3 SqlSession session object

SqlSession instance is a very powerful class in MyBatis. Here you will see all the methods for executing statements, committing or rolling back transactions, and obtaining mapper instances.
The main methods of executing statements are:

<T> T selectOne(String statement, Object parameter) //Can be used for a single query
<E> List<E> selectList(String statement, Object parameter) //Can be used when querying multiple pieces of information
int insert(String statement, Object parameter) //newly added
int update(String statement, Object parameter) //to update
int delete(String statement, Object parameter) //delete

The main methods of operating transactions are:

void commit()  //Call transaction
void rollback() //Rollback transaction

7.2 introduction to the basic principle of mybatis

Core configuration file: sqlmapconfig XML unique file, configure data source and transaction, and introduce mapping configuration file
Mapping profile: xxxmapper The XML team member has configured the SQL to be executed, incoming parameters, outgoing parameters, etc. there may be multiple files

sqlSessionFactory is built by new sqlsessionfactorybuilder() build(in)
build(in) does two things:
(1) Initialize configuration: use dom4j to parse the configuration file, encapsulate the configuration in the element configuration file into MappedStatement objects, and encapsulate these MappedStatement objects into a Map collection
(2) sqlSessionFactory factory object created
sqlSession is a session object. It does not directly operate the database and is delegated to the Executor to operate
Executor: the executor, which executes JDBC operations and obtains the value of the MappedStatement corresponding to the key value

VIII. Development and use of dao layer of Mybatis

8.1 traditional development methods

mapper is equivalent to dao in development

  1. Write UserMapper interface
public interface UserMapper {

	public List<User> findAll() throws Exception;
}
  1. Write UserMapper implementation
public class UserMapperImpl implements UserMapper { 
	@Override
	public List<User> findAll() throws Exception {
		// Load profile
		InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
		// Get SqlSessionFactory factory object
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		// Get SqlSe session object
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// Execute sql
		List<User> list = sqlSession.selectList("UserMapper.findAll");
		// Release resources
		sqlSession.close(); 
		return list;
	}
}
  1. Write usermapper 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">
<!--Query all-->
<select id="findAll" resultType="user"> 
	select * from user
</select>
</mapper>
  1. test
@Test
public void testFindAll() throws Exception {
// Create UserMapper implementation class
UserMapper userMapper = new UserMapperImpl();
// Execute query
List<User> list = userMapper.findAll(); for (User user : list) {
System.out.println(user);
}
}
  1. Knowledge summary
    Traditional development mode
1. to write UserMapper Interface
2. to write UserMapper realization
3. to write UserMapper.xml

Traditional way of thinking:
1. Duplicate mybatis template code exists in the implementation class
2. When the class calls the method, the sql statement in xml is hard coded into java code
Thinking: can I write only interfaces, not implementation classes. Write only interfaces and mapper XML?

1. to write UserMapper Interface

3. to write UserMapper.xml

Because the use of sqlsession in dao (mapper) implementation class is very similar. Therefore, mybatis provides a dynamic proxy for the interface.

8.2 agent development mode

1. Introduction
The development of persistence layer is realized by using the interface agent method of Mybatis, which is the mainstream of entering the enterprise later.
The development based on interface proxy only needs programmers to write Mapper interface, and Mybatis framework will dynamically generate the object of implementation class for us.
This development method requires us to follow certain specifications:

  • Mapper. The namespace in the XML Mapping file is the same as the fully qualified name of the mapper interface
  • Mapper interface method name and mapper The id of each statement defined in the XML Mapping file is the same
  • Mapper interface method input parameter type and mapper The parameterType of each sql defined in the XML Mapping file is of the same type
  • Mapper interface method output parameter type and mapper The resultType of each sql defined in the XML Mapping file is the same

Mapper interface development method only requires programmers to write mapper interface (equivalent to Dao interface), which is based on the interface by Mybatis framework
Define the dynamic proxy object that creates the interface. The method body of the proxy object is the same as the implementation class method of the Dao interface above.

2. Write UserMapper interface

public interface UserMapper {


	public List<User> findAll() throws Exception;

   /*Query user by id*/
    public User findUserById(int id);
}

3. Write usermapper 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.lagou.mapper.UserMapper">
	<!--Query all-->
	<select id="findAll" resultType="user"> 
		select * from user
	</select>
   <!-- according to id Query user -->
    <select id="findUserById" parameterType="int" resultType="user">
        select * from  user where id=#{id}
    </select>
</mapper>

4. Test

@Test
public void testFindAll() throws Exception {
	// Load core profile
	InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
	// Get SqlSessionFactory factory object
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
	// Get SqlSession session object
	SqlSession sqlSession = sqlSessionFactory.openSession();
	// Get Mapper proxy object
	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
	// Execute query
	List<User> list = userMapper.findAll(); 
	for (User user : list) {
		System.out.println(user);
	}
	// Release resources
	sqlSession.close();
}

public class MybatesTest {

    /*
     * mybatis mapper proxy test
     * */
    @Test
    public void test1() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //Currently, the returned proxy object is actually generated based on UserMapper: bottom layer: JDK dynamic proxy, actual type: proxy
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.findUserById(1);

        System.out.println(user);
    }
}

sqlMapConfig. Modify in XML:

<!--Load mapping configuration-->
    <mappers>
        <!-- <mapper resource="com/lagou/mapper/UserMapper.xml"></mapper>-->
        <!-- Use this method: the interface and the mapping file are synchronized with the same name-->
        <!-- <mapper class="com.lagou.mapper.UserMapper"></mapper>-->
        <!--Batch Load Mapping,Most commonly used-->
        <package name="com.lagou.mapper"/>
    </mappers>

5. Internal execution principle of mybatis based on interface proxy mode
Our persistence layer now has only one interface, and the interface does not actually work. Who is doing the actual work of query?
Let's trace the source code:
1. By tracing the source code, we will find that the mapper we use is actually a proxy object generated by MapperProxy proxy.

2. Tracing the invoke method of MapperProxy will find that it finally calls mappermethod execute(sqlSession, args)

3. After entering the execute method, you will find that the final work is sqlSession

Keywords: Java Database Spring

Added by MarineX69 on Sat, 22 Jan 2022 17:06:44 +0200