Mybatis Integrated spring Detailed Tutorial (with ideas)

Keywords: Mybatis Spring xml JDBC

Articles Catalogue


Mybatis Integration spring is actually the integration of SM in SSM framework.

1. Integration Thought

Integration thinking is actually the core of Mybatis Integration spring
1. SqlSessionFactory objects should be placed in the spring container as singletons. Spring defaults to singletons.
2. In the traditional development of dao, sqlsession objects should be obtained from spring container.
3. In the form of Mapper proxy, the proxy object of mapper should be obtained directly from the spring container.
4. Connection of database and transaction management of database connection pool are handed over to spring container.

2. Integrating jar packages needed

1. spring's jar package
2. Mybatis jar package
3. Spring+mybatis package.
4. Mysql's database-driven jar package.
5. The jar package of the database connection pool.
If you have a jar bag, I hope you all have it. Otherwise, I would be embarrassed by QAQ.

3. Integration steps

3.1. Creating Engineering

Create a java project as follows:

3.2. Importing jar packages

The jar package mentioned earlier needs to be imported as follows:

3.3. Add configuration files

1.mybatisSpring configuration file
2. The configuration file sqlmapConfig.xml
a) Database connection and connection pool
b) Transaction management (temporarily not configurable)
c)sqlsessionFactory object, configured in spring container
D) The mapeer proxy object or dao implementation class is configured in the spring container.

Create a copy of the resource folder config to add the configuration file, as shown below

3.3.1. Configure SqlMapConfig.xml

The configuration file is SqlMapConfig.xml, as follows:

<?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>
	<!-- Setting aliases -->
	<typeAliases>
		<!-- 2. Specifying a scan package will alias all classes in the package. The name of the alias is the class name, which is insensitive to case. -->
		<package name="com.gx.mybatis.pojo" />
	</typeAliases>

</configuration>

3.3.2.applicationContext.xml

SqlSession FactoryBean belongs to the jar package mybatis-spring
mybatis is another architecture for spring, requiring the integration of jar packages.

Add mybatis-spring-1.2.2.jar source code to the project, as shown below

As shown in the figure below, the icon changes to indicate that the source code was loaded successfully:

Integrating Mybatis requires SqlSession FactoryBean, located in the following figure:

applicationContext.xml, which is configured as follows

Because of the original Dao development, so

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

   <!-- Loading configuration files -->
   <context:property-placeholder location="classpath:db.properties" />

	<!-- Database connection pool -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>

	<!-- To configure SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- To configure mybatis Core Profile -->
		<property name="configLocation" value="classpath:SqlMapConfig.xml" />
		<!-- Configuring data sources -->
		<property name="dataSource" ref="dataSource" />
	</bean>
</beans>
3.3.3. Configure db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

3.3.4. Configure log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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
3.3.5. Effect:

The final effect of the added configuration file is as follows:

So far, the environment will build OK!!!!

4. Two Implementations of Dao Development

1. Development of Original dao
2. Using Mapper Agent Form to Develop
a) Configure Mapper proxy directly
b) Configuring Mapper Agents with Scan Packets

Demand:
1. Implementing queries based on user id
2. Implementing Fuzzy Query Based on User Name
3. Adding Users

4.1. Create pojo

public class User {
	private int id;
	private String username;// User Name
	private String sex;// Gender
	private Date birthday;// Birthday
	private String address;// address

get/set. . . 
}

4.2. Development of Traditional dao (I)

The original DAO development interface + implementation class to complete.
Need dao implementation class needs to inherit SqlsessionDaoSupport class

4.2.1. Implementing Mapper.xml

Write the User.xml configuration file as follows:

<?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="test">
	<!-- According to the user id query -->
	<select id="queryUserById" parameterType="int" resultType="user">
		select * from user where id = #{id}
	</select>

	<!-- Fuzzy Query Users Based on User Name -->
	<select id="queryUserByUsername" parameterType="string"
		resultType="user">
		select * from user where username like '%${value}%'
	</select>

	<!-- Adding users -->
	<insert id="saveUser" parameterType="user">
		<selectKey keyProperty="id" keyColumn="id" order="AFTER"
			resultType="int">
			select last_insert_id()
		</selectKey>
		insert into user
		(username,birthday,sex,address)
		values
		(#{username},#{birthday},#{sex},#{address})
	</insert>

</mapper>
4.2.2. Load Mapper.xml

The SqlMapConfig is configured as follows:

4.2.3. Implementing UserDao Interface
public interface UserDao {
	/**
	 * Query users according to id
	 * 
	 * @param id
	 * @return
	 */
	User queryUserById(int id);

	/**
	 * Fuzzy Query User List Based on User Name
	 * 
	 * @param username
	 * @return
	 */
	List<User> queryUserByUsername(String username);

	/**
	 * Preservation
	 * 
	 * @param user
	 */
	void saveUser(User user);

}
4.2.4. Write UserDaoImpl implementation interface and inherit SqlSession DaoSupport

Write the DAO implementation class, which must inherit SqlSession DaoSupport
SqlSession DaoSupport provides getSqlSession() method to obtain SqlSession

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
	@Override
	public User queryUserById(int id) {
		// Get SqlSession
		SqlSession sqlSession = super.getSqlSession();

		// Use SqlSession to perform operations
		User user = sqlSession.selectOne("queryUserById", id);

		// Don't close sqlSession

		return user;
	}

	@Override
	public List<User> queryUserByUsername(String username) {
		// Get SqlSession
		SqlSession sqlSession = super.getSqlSession();

		// Use SqlSession to perform operations
		List<User> list = sqlSession.selectList("queryUserByUsername", username);

		// Don't close sqlSession

		return list;
	}

	@Override
	public void saveUser(User user) {
		// Get SqlSession
		SqlSession sqlSession = super.getSqlSession();

		// Use SqlSession to perform operations
		sqlSession.insert("saveUser", user);

		// Without committing, transactions are managed by spring
		// Don't close sqlSession
	}
}

4.2.4.1. SqlSession DaoSupport source code

The implementation class must inherit SqlSession DaoSupport SqlSession DaoSupport to provide getSqlSession() method to obtain SqlSession

4.2.5. Configure dao

Configure dao implementation classes into spring containers

<!-- Dao Original Dao -->
	<bean id="userDao" class="com.gx.mybatis.dao.UserDaoImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
	</bean>
4.2.6. Create tests

Creating test methods allows you to create test Junit use cases directly.
Create as shown in the figure below.


The test methods are as follows:

public class UserDaoTest {
	private ApplicationContext context;

	@Before
	public void setUp() throws Exception {
		this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
	}

	@Test
	public void testQueryUserById() {
		// Get userDao
		UserDao userDao = this.context.getBean(UserDao.class);

		User user = userDao.queryUserById(1);
		System.out.println(user);
	}

	@Test
	public void testQueryUserByUsername() {
		// Get userDao
		UserDao userDao = this.context.getBean(UserDao.class);

		List<User> list = userDao.queryUserByUsername("Zhang");
		for (User user : list) {
			System.out.println(user);
		}
	}

	@Test
	public void testSaveUser() {
		// Get userDao
		UserDao userDao = this.context.getBean(UserDao.class);

		User user = new User();
		user.setUsername("Xiahou Longkeng");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("Three countries");
		userDao.saveUser(user);
		System.out.println(user);
	}
}

5.Mapper Agent Form Development dao (2)

5.1. Implementing Mapper.xml

Write the UserMapper.xml configuration file as follows:

<?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="cn.itcast.mybatis.mapper.UserMapper">
	<!-- According to the user id query -->
	<select id="queryUserById" parameterType="int" resultType="user">
		select * from user where id = #{id}
	</select>

	<!-- Fuzzy Query Users Based on User Name -->
	<select id="queryUserByUsername" parameterType="string"
		resultType="user">
		select * from user where username like '%${value}%'
	</select>

	<!-- Adding users -->
	<insert id="saveUser" parameterType="user">
		<selectKey keyProperty="id" keyColumn="id" order="AFTER"
			resultType="int">
			select last_insert_id()
		</selectKey>
		insert into user
		(username,birthday,sex,address) values
		(#{username},#{birthday},#{sex},#{address})
	</insert>
</mapper>
5.2. Implementing UserMapper Interface
public interface UserMapper {
	/**
	 * Query according to user id
	 * 
	 * @param id
	 * @return
	 */
	User queryUserById(int id);

	/**
	 * Fuzzy Query Users Based on User Name
	 * 
	 * @param username
	 * @return
	 */
	List<User> queryUserByUsername(String username);

	/**
	 * Adding users
	 * 
	 * @param user
	 */
	void saveUser(User user);
}

5.3. Way 1: Configure the mapper agent

Add configuration in applicationContext.xml
MapperFactoryBean is also part of the mybatis-spring integration package

<!-- Mapper Agent development mode 1, configuration Mapper Proxy object -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
	<!-- To configure Mapper Interface -->
	<property name="mapperInterface" value="com.gx.mybatis.mapper.UserMapper" />
	<!-- To configure sqlSessionFactory -->
	<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

5.4. Create tests
public class UserMapperTest {
	private ApplicationContext context;

	@Before
	public void setUp() throws Exception {
		this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
	}

	@Test
	public void testQueryUserById() {
		// Get Mapper
		UserMapper userMapper = this.context.getBean(UserMapper.class);

		User user = userMapper.queryUserById(1);
		System.out.println(user);
	}

	@Test
	public void testQueryUserByUsername() {
		// Get Mapper
		UserMapper userMapper = this.context.getBean(UserMapper.class);

		List<User> list = userMapper.queryUserByUsername("Zhang");

		for (User user : list) {
			System.out.println(user);
		}
	}
	@Test
	public void testSaveUser() {
		// Get Mapper
		UserMapper userMapper = this.context.getBean(UserMapper.class);

		User user = new User();
		user.setUsername("Angela");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("China");

		userMapper.saveUser(user);
		System.out.println(user);
	}
}
5.5. Mode 2: Scanning package configuration mapper (commonly used for development)
<! - Mapper Agent Development Mode II, Scanning Packet Configuration Agent - >
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<! - Configure Mapper interface - >
	<property name="basePackage" value="com.gx.mybatis.mapper" />
</bean>

The id of each mapper proxy object is the class name, initially lowercase

6. Summary of Dao's Development Method

Posted by AlexP on Sat, 27 Jul 2019 19:37:34 -0700