Mybatis integrated spring (for white)

@ [TOC] Mybatis integrated spring is actually integrated framework SSM SM integration.

1. impoundment

Integration idea is actually Mybatis integration of core spring

1, SqlSessionFactory spring containers should be placed in the object as a single present embodiment , spring default single embodiment. 2, the traditional development dao, the subject should be obtained from the spring sqlsession container. 3, Mapper proxy form should be obtained directly from the proxy object mapper spring vessel. 4, database connection and transaction management database connection pool are to spring container to complete.

2. The need to integrate the jar package

1, spring jar package 2, Mybatis jar package 3, Spring + mybatis integrated package. 4, Mysql database driver jar package. 5, the database connection pool jar package.

jar package, I hope all of you are the best, otherwise I am very embarrassed QAQ

3. Integration Steps

3.1. Creating Project

Create a java project in the following figure:

Here Insert Picture Description

3.2. Import jar package

jar package introducing the aforementioned needs, as shown below:

Here Insert Picture Description

3.3. Join Profiles

1.mybatisSpring profile 2. The profile sqlmapConfig.xml a) connection pool database connections, and b) a transaction management (temporarily may not be arranged) c) sqlsessionFactory objects, arranged to spring vessel d) mapeer proxy object implemented or dao class spring configured into a container.

Create a resource folder config configuration file copy to join, as shown below

Here Insert Picture Description

3.3.1. Configuration 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>
	<!-- 设置别名 -->
	<typeAliases>
		<!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
		<package name="com.gx.mybatis.pojo" />
	</typeAliases>

</configuration>

复制代码
3.3.2.applicationContext.xml

SqlSessionFactoryBean belong mybatis-spring for spring is this jar package, mybatis is another architecture, the need to integrate jar package.

Mybatis-spring-1.2.2.jar added in the project source code, as shown below

Here Insert Picture Description
Here Insert Picture Description

Effect, as shown below, the icon changes to indicate successful loading Source:

Here Insert Picture Description
Integration is required Mybatis SqlSessionFactoryBean, position as shown below:
Here Insert Picture Description

applicationContext.xml, arranged as follows

Since the original development of Dao, 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">

   <!-- 加载配置文件 -->
   <context:property-placeholder location="classpath:db.properties" />

	<!-- 数据库连接池 -->
	<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>

	<!-- 配置SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 配置mybatis核心配置文件 -->
		<property name="configLocation" value="classpath:SqlMapConfig.xml" />
		<!-- 配置数据源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
</beans>
复制代码
3.3.3. Configuration 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. Configuration 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 ultimate effect of the profile is added as follows:

Here Insert Picture Description
So far built environment on the OK! ! ! !

4. Development of two implementations of Dao

1, 2 original dao development mode, the use of the agent in the form of development Mapper embodiment a) Direct Mapper proxy configuration b) scanning the package configuration Mapper Agent

Requirements: 1. To achieve 2. 3. Add implement fuzzy query based on user name user query based on user id

4.1. Creating pojo

public class User {
	private int id;
	private String username;// 用户姓名
	private String sex;// 性别
	private Date birthday;// 生日
	private String address;// 地址

get/set。。。
}

复制代码

4.2. Dao traditional development mode (Mode 1)

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

4.2.1. Achieve Mapper.xml

User.xml write the 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">
	<!-- 根据用户id查询 -->
	<select id="queryUserById" parameterType="int" resultType="user">
		select * from user where id = #{id}
	</select>

	<!-- 根据用户名模糊查询用户 -->
	<select id="queryUserByUsername" parameterType="string"
		resultType="user">
		select * from user where username like '%${value}%'
	</select>

	<!-- 添加用户 -->
	<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

SqlMapConfig configured in the following figure:

Here Insert Picture Description

4.2.3. Interface to achieve UserDao
public interface UserDao {
	/**
	 * 根据id查询用户
	 * 
	 * @param id
	 * @return
	 */
	User queryUserById(int id);

	/**
	 * 根据用户名模糊查询用户列表
	 * 
	 * @param username
	 * @return
	 */
	List<User> queryUserByUsername(String username);

	/**
	 * 保存
	 * 
	 * @param user
	 */
	void saveUser(User user);

}
复制代码
4.2.4. Writing UserDaoImpl implement interfaces and inherit SqlSessionDaoSupport

Write DAO implementation class, the implementation class must inherit SqlSessionDaoSupport SqlSessionDaoSupport provide getSqlSession () method to get SqlSession

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

		// 使用SqlSession执行操作
		User user = sqlSession.selectOne("queryUserById", id);

		// 不要关闭sqlSession

		return user;
	}

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

		// 使用SqlSession执行操作
		List<User> list = sqlSession.selectList("queryUserByUsername", username);

		// 不要关闭sqlSession

		return list;
	}

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

		// 使用SqlSession执行操作
		sqlSession.insert("saveUser", user);

		// 不用提交,事务由spring进行管理
		// 不要关闭sqlSession
	}
}

复制代码
4.2.4.1. SqlSessionDaoSupport source

Implementation class must inherit SqlSessionDaoSupport SqlSessionDaoSupport provide getSqlSession () method to get SqlSession

Here Insert Picture Description

4.2.5. Configuration dao

The implementation class dao spring arranged to vessel

<!-- Dao原始Dao -->
	<bean id="userDao" class="com.gx.mybatis.dao.UserDaoImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
	</bean>
复制代码
4.2.6. Create a test

Create a test method, you can create a direct test Junit use cases. Created as shown in FIG.

Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

Preparation of 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() {
		// 获取userDao
		UserDao userDao = this.context.getBean(UserDao.class);

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

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

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

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

		User user = new User();
		user.setUsername("夏侯惇坑");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("三国");
		userDao.saveUser(user);
		System.out.println(user);
	}
}

复制代码

5.Mapper proxy form development dao (second approach)

5.1. Implement Mapper.xml

UserMapper.xml write the 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">
	<!-- 根据用户id查询 -->
	<select id="queryUserById" parameterType="int" resultType="user">
		select * from user where id = #{id}
	</select>

	<!-- 根据用户名模糊查询用户 -->
	<select id="queryUserByUsername" parameterType="string"
		resultType="user">
		select * from user where username like '%${value}%'
	</select>

	<!-- 添加用户 -->
	<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. Implement UserMapper Interface
public interface UserMapper {
	/**
	 * 根据用户id查询
	 * 
	 * @param id
	 * @return
	 */
	User queryUserById(int id);

	/**
	 * 根据用户名模糊查询用户
	 * 
	 * @param username
	 * @return
	 */
	List<User> queryUserByUsername(String username);

	/**
	 * 添加用户
	 * 
	 * @param user
	 */
	void saveUser(User user);
}

复制代码
5.3 Method 1: Configure proxy mapper

Add Configuration MapperFactoryBean in applicationContext.xml also belongs mybatis-spring integrated package

<!-- Mapper代理的方式开发方式一,配置Mapper代理对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
	<!-- 配置Mapper接口 -->
	<property name="mapperInterface" value="com.gx.mybatis.mapper.UserMapper" />
	<!-- 配置sqlSessionFactory -->
	<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

复制代码
5.4. Create a test
public class UserMapperTest {
	private ApplicationContext context;

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

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

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

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

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

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

		User user = new User();
		user.setUsername("安琪拉稀");
		user.setSex("1");
		user.setBirthday(new Date());
		user.setAddress("中国");

		userMapper.saveUser(user);
		System.out.println(user);
	}
}
复制代码
5.5 Second way: scanning configuration packet form Mapper (common development)
<!-- Mapper代理的方式开发方式二,扫描包方式配置代理 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 配置Mapper接口 -->
	<property name="basePackage" value="com.gx.mybatis.mapper" />
</bean>
复制代码

Each id mapper proxy object is the class name, the first letter lowercase

6, developed Dao implementation of a summary map

Here Insert Picture Description

Guess you like

Origin juejin.im/post/5de5af7a5188255ee5387067