MyBatis configuration files and mapper are explained in detail here

The basic concept

1.1 the ORM framework

The Object/Relational Mapping (ORM) framework allows you to manipulate databases in an object-oriented manner by describing the Mapping between Java objects and database tables.For example, using JAVA to query a database without using ORM looks like this

book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // I over simplify ...
while (row = data.next())
{
     book = new Book();
     book.setAuthor(row.get('author');
     book_list.add(book);
}
Copy the code

Using ORM allows you to do this

book_list = BookTable.query(author="Linus");
Copy the code

Common ORM frameworks are Hibernate and MyBatis.

MyBatis is a Java-based persistence layer framework that uses simple XML or annotations for configuration and raw mapping to map interfaces and Java’s POJOs (Plain Old Java Objects) into records in the database. The main differences between the two frameworks are as follows.

Hibernate MyBatis
A framework for full table mapping that only needs to provide POJOs and mapping relationships A semi-automatic mapping framework that requires manual matching of POJO, SQL, and mapping relationships
A powerful, complex, indirect, fully automated persistence layer framework Compact, simple, straightforward, semi-automated persistence layer framework

1.2 MyBatis working process

  1. Read MyBatis configuration file: MyBatis -config. XML is the global configuration file of MyBatis, which configures the operating environment and other information of MyBatis, such as database connection information.

  2. Loading a mapping file: A mapping file is an SQL mapping file that contains SQL statements used to operate the database. The file must be loaded in the MyBatis configuration file MyBatis -config. XML. The mybatis-config. XML file can load multiple mapping files, each corresponding to a table in the database.

  3. Construct session Factory: Build session factory SqlSessionFactory with MyBatis environment configuration information.

  4. Create session object: The session factory creates the SqlSession object, which contains all the methods for executing SQL statements.

  5. Executor Executor: MyBatis defines an Executor interface to operate the database. It dynamically generates SQL statements that need to be executed based on the parameters passed by SqlSession and maintains the query cache.

  6. MappedStatement object: In the Executor interface execution method, there is a parameter of type MappedStatement. This parameter encapsulates mapping information and stores information such as the ID and parameter of the SQL statement to be mapped.

  7. Input parameter mapping: Input parameter types can be collection types such as Map and List, as well as basic data types and POJO types. The input parameter mapping procedure is similar to the JDBC procedure for setting parameters on a preparedStatement object.

  8. Output result mapping: Output result types can be collection types such as Map and List, as well as basic data types and POJO types. The output result mapping process is similar to the JDBC result set parsing process.

Mybatis instance

1. Create log4j.properties in the SRC /main/resource folder

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.dao=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Copy the code

If the configuration file cannot be found, create log4j2.xml in the SRC /main/resource folder


      

<Configuration status="warn">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%m%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>
Copy the code

2. Create persistent classes

public class MyUser {
    private Integer uid;/ / the primary key
    private String uname;
    private String usex;
    public Integer getUid(a) {
        return uid;
    }
    // Omit the get and set methods, otherwise it is too long
    @Override
    public String toString(a) {
        return "User [uid=" + uid +",uname=" + uname + ",usex=" + usex +"]"; }}Copy the code

3. Creating a Mapping File

Create the com.mapper package in which the mapping file usermapper.xml is created.


      
<! DOCTYPEmapper
PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper">
	<! SQL > select * from user where uid = 1;
	<select id="selectUserById" parameterType="Integer"
		resultType="com.po.MyUser">
		select * from user where uid = #{uid}
	</select>
	<! -- Query all user information -->
	<select id="selectAllUser" resultType="com.po.MyUser">
		select * from user
	</select>
	<! Add user #{uname} to com.mybatis. Po.myuser
	<insert id="addUser" parameterType="com.po.MyUser">
		insert into user (uid,uname,usex)
		values(#{uid},#{uname},#{usex})
	</insert>
	<! -- Modify a user -->
	<update id="updateUser" parameterType="com.po.MyUser">
		update user set uname =
		#{uname},usex = #{usex} where uid = #{uid}
	</update>
	<! -- Delete a user -->
	<delete id="deleteUser" parameterType="Integer">
		delete from user where uid
		= #{uid}
	</delete>
</mapper>
Copy the code
  • In the mapping file, the
    element is the root of the configuration file and contains a namespace attribute, which is usually set to “package name +SQL map name” and specifies a unique namespace.

  • The information in the child elements < SELECT >, < INSERT >,

    , and < DELETE > is the configuration used to perform the query, add, modify, and delete operations. (Add, delete, change and check)

  • SQL statement, “#{}” represents a placeholder, equivalent to “? “, and “#{uid}” indicates that the name of the parameter to be received by the placeholder is UID.

4. Create the MyBatis configuration file

In the SRC directory, create the MyBatis core configuration file MyBatis -config. XML, configure the database environment and mapping file location.


      
<! DOCTYPEconfiguration
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<! -- Configure the environment -->
	<environments default="development">
		<environment id="development">
			<! -- Transaction management using JDBC -->
			<transactionManager type="JDBC"/>
			<dataSource type="POOLED">
				<! MySQL database driver -->
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<! URL to connect to database -->
				<property name="url" value="jdbc:mysql://localhost:3306/sql_springtest? characterEncoding=utf8"/>
				<property name="username" value="root"/>
				<property name="password" value="20011017lh"/>
			</dataSource>
		</environment>
	</environments>
	<mappers>
	<! Map file location -->
	<mapper resource="com/mapper/UserMapper.xml"/>
	</mappers>
</configuration>
Copy the code

5. Creating a test class

Use the input stream to read the configuration file, build the SqlSessionFactory object according to the configuration information, create SqlSession object through the SqlSessionFactory object, use the SqlSession object method to perform database operations.

package com.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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 com.po.MyUser;
public class MyBatisTest {
	public static void main(String[] args) {
		try {
			// Read the configuration file mybatis-config.xml
			InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
			// Build the SqlSessionFactory from the configuration file
			SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
			// Create a SqlSession with SqlSessionFactory
			SqlSession ss = ssf.openSession();
			SqlSession executes the SQL defined in the mapping file and returns the mapping result
			/ / com) mapper) UserMapper. SelectUserById for UserMapper. + select id in XML namespace
			// Query a user
			MyUser mu = ss.selectOne("com.mapper.UserMapper.selectUserById".1);
			System.out.println(mu);
			// Add a user
			MyUser addmu = new MyUser();
			addmu.setUid(1);
			addmu.setUname("Chen Heng 2");
			addmu.setUsex("Man 2");
						// Modify a user
			MyUser updatemu = new MyUser();
			updatemu.setUid(1);
			updatemu.setUname("Zhang");
			updatemu.setUsex("Female 1");
			ss.update("com.mapper.UserMapper.updateUser", updatemu);
			// Delete a user
			ss.delete("com.mapper.UserMapper.deleteUser".1);
			
			ss.insert("com.mapper.UserMapper.addUser",addmu);
			ss.insert("com.mapper.UserMapper.addUser",addmu);

			// Query all users
			List<MyUser> listMu = ss.selectList("com.mapper.UserMapper.selectAllUser");
			for (MyUser myUser : listMu) {
				System.out.println(myUser);
			}
			// Commit the transaction
			ss.commit();
			/ / close the SqlSession
			ss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch blocke.printStackTrace(); }}}Copy the code

Mybatis integration with Spring

As can be seen from the previous section, it is not easy to access the database directly using the SqlSession of MyBatis framework. MyBatis framework focuses on SQL mapping files, for convenience, MyBatis and Spring integration.

  • By integrating with Spring, MyBatis SessionFactory is built by Spring. The MyBatis factory needs to be configured in the Spring configuration file
<! Configure MyBatis factory and specify data source, integrate with MyBatis  
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
    <property name="dataSource" ref="dataSource" />  
    <! -- configLocation property value is MyBatis core configuration file -->
    <property name="configLocation" value="classpath:com/mybatis/mybatis-config.xml"/>
</bean>  
Copy the code
  • The simplest way to use Spring to manage MyBatis’ data manipulation interface is the integration based on MapperScannerConfigurer. You need to use@MapperAnnotations annotate the data access layer interface and enable scanning in the XML
<! --Mapper agent development, using Spring to automatically scan MyBatis interface and assemble (Spring will specify package all annotated by @mapper interface automatically assemble MyBatis mapping interface) --> 
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
   <! -- Mybatis -- Spring component scanner -->
   <property name="basePackage" value="com.dao"/>
   <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
Copy the code

Example:

1. Create the application and import the related JAR packages

2. Create persistent classes

3. Create SQL mapping files and MyBatis core configuration files

Create com.mybatis package, create mybatis core configuration file mybatis-config. XML and SQL mapping file usermapper.xml in this package.

mybatis-config.xml


      
<! DOCTYPEconfiguration
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <! Tell MyBatis where to find the mapping file.
	 <mappers>
        <mapper resource="com/mybatis/UserMapper.xml"/>
 	</mappers>
</configuration>
Copy the code

UserMapper. In XMLnamespaceNo longer when integrated with Springcom.mapper.UserMapperbutcom.dao.UserDao, the rest is the same as in the previous section

4. Create a com.dao package. In this package, create a UserDao interface and annotate the interface with @mapper as Mapper.

package com.dao;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import com.po.MyUser;
@Repository("userDao")
@Mapper
/* Use Spring to automatically scan and assemble MyBatis interfaces (Spring will automatically assemble all interfaces annotated by @mapper annotations in the specified package as MyBatis mapping interfaces */
public interface UserDao {
	/** * Interface methods correspond to id */ in the SQL mapping file usermapper.xml
	public MyUser selectUserById(Integer uid);
	public List<MyUser> selectAllUser(a);
	public int addUser(MyUser user);
	public int updateUser(MyUser user);
	public int deleteUser(Integer uid);
}
Copy the code

5. Creating a log file

Create the log file log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.dao=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Copy the code

6. Create the control layer Create the com.Controller package, create the UserController class, and call the methods in the UserDao interface in that class.

package com.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.dao.UserDao;
import com.po.MyUser;
@Controller("userController")
public class UserController {
	@Autowired
	private UserDao userDao;
	public void test(a) {
		// Query a user
		MyUser auser = userDao.selectUserById(1);
		System.out.println(auser);
		System.out.println("= = = = = = = = = = = = = = = =");
		// Add a user
		MyUser addmu = new MyUser();
		addmu.setUname("Chen Heng");
		addmu.setUsex("Male");
		int add = userDao.addUser(addmu);
		System.out.println("Added" + add + "A record");
		System.out.println("= = = = = = = = = = = = = = = =");
		// Modify a user
		MyUser updatemu = new MyUser();
		updatemu.setUid(1);
		updatemu.setUname("Zhang");
		updatemu.setUsex("Female");
		int up = userDao.updateUser(updatemu);
		System.out.println("Modified" + up + "A record");
		System.out.println( "= = = = = = = = = = = = = = = =");
		// Delete a user
		int dl = userDao.deleteUser(9);
		System.out.println("Deleted" + dl + "A record");
		System.out.println("= = = = = = = = = = = = = = = =");
		// Query all users
		List<MyUser> list = userDao.selectAllUser();
		for(MyUser myUser : list) { System.out.println(myUser); }}}Copy the code

7. Create a Configuration file for Spring

Configure data source, MyBatis factory, Mapper agent development and other information.

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <! <context:component-scan base- specifies the package (including subpackages) to scan for the annotation to take effect --> <context:component-scan base-package="com.dao"/>
    <context:component-scan base-package="com.controller"/ > <! -- Configure data source --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/springtest? characterEncoding=utf8" />
        <property name="username" value="root" />
        <property name="password" value="root"/ > <! -- Maximum number of connections --> <property name="maxTotal" value="30"/ > <! -- Maximum number of free connections --> <property name="maxIdle" value="10"/ > <! -- initialize connection number --> <property name="initialSize" value="5"/> </bean> <! -- Add transaction support (test class seems to use transaction management) --> <bean id="txManager"   
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
        <property name="dataSource" ref="dataSource"/> </bean> <! <tx:annotation- Driven Transaction - Manager = <tx:annotation- Driven Transaction - Manager ="txManager"/ > <! Configure MyBatis factory, specify data source, integrate with MyBatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"/ > <! -- configLocation property value is MyBatis core configuration file --> <property name="configLocation" value="classpath:com/mybatis/mybatis-config.xml"/> </bean> <! -Mapper agent development, using Spring to automatically scan the interface of MyBatis and assemble (Spring will specify all packages@MapperAnnotated interfaces are automatically assembled into MyBatis mapping interfaces) --> <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"> <! -- Mybatis - Spring component scanner --> <property name="basePackage" value="com.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>
Copy the code

8. In the package com.controller, create the test class TestController

package com.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestController {
	public static void main(String[] args) {
		ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserController uc = (UserController)appCon.getBean("userController"); uc.test(); }}Copy the code