MyBatis learning notes 2

MyBatis study notes - 2

1. Write MyBatis project using Mapper's interface

1.1 Mapper interface

The MyBatis framework abandons Dao's implementation class and directly locates the corresponding SQL statement in the mapping file Mapper to operate the DB. This implementation of Dao is called the dynamic proxy method of Mapper interface.

Mapper dynamic proxy mode does not require programmers to implement Dao interface. The interface is implemented by the dynamic agent automatically generated by MyBatis combined with the mapping file.

2. Mapper implementation steps

2.1 interface preparation

package com.xaf.mapper;
import com.xaf.pojo.Team;
import java.util.List;
public interface TeamMapper {
	List<Team> queryAll();
	Team queryById(int teamId);
	int add(Team team);
	int update(Team team);
	int del(int teamId);
}

Of course, we need to create the corresponding xml 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="Fully qualified name, fully qualified name of interface "-->
<mapper namespace="com.xaf.mapper.TeamMapper">
	<!--Omit content, copy Team.xml Content in-->
</mapper>

Register the mapping file in the mybatis.xml configuration file

<mappers>
	<!--Omit others-->
	<mapper resource="com/xaf/mapper/TeamMapper.xml"/>
</mappers>

2.2 getMapper method to obtain proxy object

Simply call the getMapper() method of SqlSession to obtain the implementation class object of the specified interface.

package com.xaf.test;
import com.xaf.dao.TeamDao;
import com.xaf.dao.TeamDaoImpl;
import com.xaf.mapper.TeamMapper;
import com.xaf.pojo.Team;
import com.xaf.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
import java.util.List;
/**
* ClassName: TeamDaoTest
* TeamMapper Test class for
* @version 1.0
*/
public class TeamMapperTest {
	private SqlSession sqlSession=MybatisUtil.getSqlSession();
	@Test
	public void test01(){
		TeamMapper teamDao= sqlSession.getMapper(TeamMapper.class);
		//add to
		Team team=new Team();
		team.setTeamName("warrior");
		team.setLocation("Jinzhou");
		team.setCreateTime(new Date());
		int num=teamDao.add(team);
		sqlSession.commit();//It must be submitted for the addition, deletion and modification to take effect
		System.out.println(num);
		//to update
		Team team1 = teamDao.queryById(1001);
		team1.setTeamName("XiaoAiFu My team");
		num = teamDao.update(team1);
		sqlSession.commit();//It must be submitted for the addition, deletion and modification to take effect
		System.out.println(num);
		//delete
		num=teamDao.del(1001);
		sqlSession.commit();//It must be submitted for the addition, deletion and modification to take effect
		System.out.println(num);
		//Query all
		List<Team> teams = teamDao.queryAll();
		teams.forEach(t-> System.out.println(t));
	}
}

Of course, the above operations only let you know how to use Mapper to dynamically proxy your own projects, and you don't need to copy and paste.

3. The difference between #{} and ${}

3.1 #{}

#{}: represents a placeholder that tells Mybatis to use the actual parameter value instead. The PrepareStatement object is used to execute the sql statement, #{...} instead of the "?" of the sql statement. This is the preferred practice in Mybatis, safe and fast.

<select id="queryById" parameterType="int" resultType="com.kkb.pojo.Team">
	select * from team where teamId=#{id}
</select>
<!--Mybatis The execution time is:
	String sql="select * from team where teamId=?";
	PreparedStatement ps = conn.prepareStatement(sql);
	ps.setInt(1,1001);
	where teamId=? Actually where teamId=#{id}
	ps.setInt(1,1001) 1001 in will replace#{id}
-->

3.2 ${}

: surface show word symbol strand primary kind for change , through know ' M y b a t i s ' send use ' {}: indicates that the string is replaced as is. Notify 'Mybatis' to use it` : indicates that the string is replaced as is, and informs' Mybatis' to replace the location with the "string" contained in the. Use Statement or PreparedStatement to connect the sql Statement with the contents of ${} '. It is generally used to replace table name, column name, sorting different columns, etc.

Example 1:

Add the following to the TeamMapper interface:

List<Team> queryByName(String teamName);
List<Team> queryByLocation(String location);

Add the following to the TeamMapper.xml configuration file:

<select id="queryByName" resultType="com.xaf.pojo.Team">
	select * from team where teamName=#{teamName}
</select>
<select id="queryByLocation" resultType="com.xaf.pojo.Team">
	select * from team where location=#{location}
</select>

Example 2:

Add the following to the TeamMapper interface:

List<Team> queryByFiled(@Param("column") String column,@Param("columnValue") String columnValue);

Add the following to the TeamMapper.xml configuration file:

<select id="queryByFiled" resultType="com.xaf.pojo.Team">
	select * from team where ${column}=#{columnValue}
</select>

This is the difference between the above configurations. The former is mostly used as a placeholder; The latter will generally inform the program in advance to replace the string and replace the string as it is.

4. Global configuration file for Mybatis

Mybatis The configuration file contains information that will affect Mybatis Behavior settings and attribute information. The top-level structure of the configuration file is as follows:
configuration(Configuration)
	properties--Properties: load external configuration files, such as the connection information of the database
	Settings--Global configuration parameters: for example, log configuration
	typeAliases--Type alias
	typeHandlers----Type processor
	objectFactory-----Object factory
	Plugins------Plug in: for example, paging plug-in
	Environments----Environment collection property object
		environment(Environment variables)
			transactionManager(Transaction manager)
			dataSource((data source)
	Mappers---Mapper: for registering mapping files

4.1 properties

Properties can be configured externally and can be replaced dynamically. We can set these properties in the child elements of the properties element (such as the properties node in the DataSource node) or configure them in the Java properties file.

There are four parameter data connected to the database in the data source. We usually put them in a special property file. The global configuration file of mybatis can read the data directly from the property file.

1. Create a jdbc.properties file in the resources directory. The file name can be customized.

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
jdbc.username=root
jdbc.password=root

2. mybatis global configuration file import properties file

<properties resource="jdbc.properties"/>

3. Use the values in the properties file

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

4.2 Settings

The extremely important adjustment settings in MyBatis will change the runtime behavior of MyBatis. For example, the log we configured is one of the applications.

<!--Configuration log-->
<settings>
	<setting name="logImpl" value="LOG4J"/>
</settings>

4.3 type aliases

Type alias sets an abbreviated name for a Java type. It is only used for XML configuration and is intended to reduce redundant fully qualified class name writing.

4.3.1 aliases already supported in mybatis

4.3.2 user defined alias

<!--Custom type alias-->
<typeAliases>
	<!--Define an alias for a single entity class-->
	<typeAlias type="com.kkb.pojo.Team" alias="Team"/>
	<!--Recommended writing method: batch define alias: scan all classes under the specified package, and define the alias as the class name. The initial case of the alias is OK-->
	<package name="com.kkb.pojo"/>
</typeAliases>

4.4 Mappers

Configuration method:

4.4.1 using resource references relative to Classpaths

Syntax:<mapper resource=""/>
Use resources relative to classpath,from classpath Path lookup file
 For example:<mapper resource="com/kkb/mapper/TeamMapper.xml" />

4.4.2 fully qualified class name of implementation class using mapper interface

grammar:<mapper class=""/>
Used mapper Fully qualified name of the interface
 Requirement: the interface and mapping files have the same name as the package
 for example<mapper class="com.kkb.mapper.GameRecordMapper"/>

4.4.3 register all mapper interface implementations in the package as mappers - Recommended

grammar:<package name=""/>
Specify all under the package Mapper Interface
 For example:<package name="com.kkb.mapper"/>
Note: this method requires Mapper Interface name and mapper The mapping files have the same name and are in the same directory.

4.5 dataSource label

The database access in Mybatis supports connection pool technology, and adopts its own connection pool technology. In the mybatis.xml configuration file of Mybatis, configure the connection pool in Mybatis through. During initialization, Mybatis creates a data source of the corresponding type according to the type attribute of the.

UNPOOLED: Data sources that do not use connection pools
POOLED:Data source using connection pool
JNDI: use JNDI Implemented data source
 The first two data sources are implemented javax.sql.DataSource Interface

4.6 transactions

4.6.1 default manual configuration

The Mybatis framework encapsulates JDBC, so the transaction control method of the Mybatis framework itself also uses the commit(). Rollback(). setAutoCommit() method of the Connection object of JDBC to set the transaction submission method. Automatic submission and manual submission.

<transactionManager type="JDBC"/>

This label specifies the transaction manager used by MyBatis. MyBatis supports two transaction manager types: JDBC and MANAGED.

The above is a further introduction to MyBatis. Thank you for reading.

Tags: Java Database SQL

Posted on Sun, 19 Sep 2021 16:28:10 -0400 by Crazy Horse