Introduction to Mybatis and coding process 2021-09-20

Keywords: Java Database Spring

Mybatis application

1 Introduction to Mybatis and coding process
2 mapper agent development method
3 global profile
4 input mapping and output mapping
5 Association query
6 delayed loading
7 dynamic SQL
8 Mybatis cache

1, What is Mybatis

Mybatis reference website: http://www.mybatis.org/mybatis-3/zh/index.html
Github source address: https://github.com/mybatis/mybatis-3
MyBatis is an excellent persistence layer framework, which supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost
With all JDBC code and manually setting parameters and obtaining result sets, it can use simple XML or annotations to configure and map SQL messages
The interface and Java POJOs(Plain Old Java Objects) are mapped into records in the database.

1.1 origin of mybatis

MyBatis was originally an open source project of apache, iBatis.
In 2010, the project was migrated from apache software foundation to google code and renamed MyBatis.
Moved to Github in November 2013.

1.2 what is ORM

Object / Relational Mapping (ORM) is developed with the object-oriented software development method
It's caused by. It is used to map the objects represented by the object model to the relational model database structure based on SQL. In this way, we are specific
When operating entity objects, you don't need to deal with complex SQL statements, just simply operate the attributes and properties of entity objects
method. ORM technology provides a bridge between objects and relationships, object-oriented data in the foreground and relational data in the database
Through this bridge to transform each other.

1.3 differences between ORM framework and MyBatis

Mybatis VS Hibernate
Performance: high vs low
Sql flexibility: high vs low
Learning threshold: low vs high
Sql configuration file: global configuration file, mapping file vs global configuration file, mapping file
ORM semi automation vs full automation
Low database independence vs high

2, Coding process

2.1 requirements description

1. Query a user information according to the user id
2. Fuzzy query user information list according to user name
3. Add user

2.2 coding process

  1. Write the global configuration file: SqlMapConfig.xml (database configuration) is integrated with Spring in practical application and uses Spring to provide configuration classes.
  2. Mapping file: xxxMapper.xml (write SQL statement)
  3. Write dao Code: xxxDao interface, xxxDaoImpl implementation class (write mybatis API)
  4. POJO class (pass parameter and result mapping object)
  5. Unit test class

2.2.1 profile settings

Write a global configuration file: SqlMapConfig.xml, which loads the corresponding Mapper.xml file.

	<properties resource="phase01/db.properties"></properties>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${db.driver}" />
				<property name="url" value="${db.url}" />
				<property name="username" value="${db.username}" />
				<property name="password" value="${db.password}" />
			</dataSource>
		</environment>
	</environments>
	<!--load Mapper file-->
	<mappers>
		<mapper resource="phase01/UserMapper.xml" />
	</mappers>

2.2.2 SqlSession interface

sqlSession.selectOne MyBatis accesses the database related interfaces, and then check the entry of the source code.

public class UserDaoImpl implements UserDao {

    private SqlSessionFactory sqlSessionFactory;

    // Inject sqlSessionFactory
    public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    public User findUserById(int id) {
        // sqlsessionFactory factory class to create sqlsession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // sqlsession interface, which is used by developers to add, delete, modify and query the database
        User user = sqlSession.selectOne("test.findUserById", id);
        return user;
    }

}

2.2.3 mapper preparation

The SQL statement is written in the select tag, the dynamic parameters are passed in #{}, the parameterType is the type of the parameter, and the result type is resultType.

	<!-- matters needing attention: -->
	<!-- 1: If parameterType Is a simple type (basic type)+String Class),#The parameter name in {} can be any -- >
	<!-- 2: If parameterType by POJO Type,#The parameter name in {} must be consistent with the attribute name in POJO -- >
	<!-- 3: If resultType by POJO Type, SELECT Column names and in POJO The attribute names in are consistent -->
	<select id="findUserById" parameterType="int"
		resultType="com.kkb.mybatis.phase01.po.User">
		SELECT * FROM user WHERE id = #{id}
	</select>

2.2.4 testing

/**
 * Test entry case
 * 
 * @author think
 *
 */
public class Test1 {

	private SqlSessionFactory sqlSessionFactory;

	@Before
	public void init() throws Exception{
		// Load the global configuration file (also load the mapping file)
		String resource = "phase01/SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// sqlsessionFactory needs to read the global configuration file information through sqlsessionFactoryBuilder
		// Builder mode
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test
	public void testFindUserById() {
		UserDao dao = new UserDaoImpl(sqlSessionFactory);
		User user = dao.findUserById(1);
		System.out.println(user);
	}
}

Posted by PHP-Nut on Mon, 20 Sep 2021 23:26:33 -0700