Dao Development Mybatis (three) Mybatis of

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/xuruanshun/article/details/102701973

table of Contents

1. development needs

2.SqlSession range of uses

3. The original development mode Dao

4.Mapper dynamic proxy mode (recommended)

5. Summary


 

Use MyBatis develop Dao, usually there are two methods,

1) Dao original development methodology (understanding)

2) Mapper to develop dynamic proxy method (recommended)

 

 

1. Development needs

MyBatis developed using DAO achieve the following functions:

1) a user query information based on user id

2) According to the information the user name fuzzy search user list

3) Add User Information

 

 

2. SqlSession range of uses

 

SqlSession encapsulates operation of the database, such as: query, insert, update, and delete.

SqlSession created by SqlSessionFactory.

SqlSessionFactory is created by SqlSessionFactoryBuilder.

 

2.1.SqlSessionFactoryBuilder

SqlSessionFactoryBuilder used to create SqlSessionFacoty, SqlSessionFacoty Once created SqlSessionFactoryBuilder do not need to, because SqlSession is created by SqlSessionFactory. Therefore SqlSessionFactoryBuilder class may be used as a tool, the optimal range of use of the method is a method in vivo i.e. a local variable.

 

2.2.SqlSessionFactory

SqlSessionFactory is an interface, the interface is defined in a different openSession overloaded methods, the optimum range during the entire application SqlSessionFactory operation, once created can be reused, typically in a single embodiment SqlSessionFactory management mode.

 

2.3.SqlSession

SqlSession is a user-oriented interface, sqlSession method defined database operation.

Each thread should have its own SqlSession instance. Examples SqlSession can not be shared, it is thread safe. Therefore the optimum range is requested or scope of the method. It must not be SqlSession reference to an instance of a class in a static field or instance field.

Open a SqlSession; we must close it after use. This usually close operation in the finally block to ensure that every time a shutdown:

SqlSession session = sqlSessionFactory.openSession();
try {
        // do work
} finally {
       session.close();
}

 

3. The original development mode Dao

Dao original development methods and interfaces need to write Dao Dao implementation class.

1. Edit UserMapper.xml mapping 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">

<mapper namespace="test">

    <!-- 根据id查询用户 -->
    <select id="queryUserById" parameterType="int" resultType="com.dayee.entity.User">
		select * from user where id = #{id}
	</select>

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

    <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.dayee.entity.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>

2.Dao Interface

package com.dayee.dao;

import com.dayee.entity.User;

import java.util.List;

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);
}

3.DaoImpl implementation class

package com.dayee.dao;

import com.dayee.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDaoImpl implements UserDao {

	private SqlSessionFactory sqlSessionFactory;

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

	@Override
	public User queryUserById(int id) {
		// 创建SqlSession
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		// 执行查询逻辑
		User user = sqlSession.selectOne("queryUserById", id);
		// 释放资源
		sqlSession.close();
		return user;
	}

	@Override
	public List<User> queryUserByUsername(String username) {
		// 创建SqlSession
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		// 执行查询逻辑
		List<User> list = sqlSession.selectList("queryUserByUsername", username);
		// 释放资源
		sqlSession.close();
		return list;
	}

	@Override
	public void saveUser(User user) {
		// 创建SqlSession
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		// 执行保存逻辑
		sqlSession.insert("saveUser", user);
		// 提交事务
		sqlSession.commit();
		// 释放资源
		sqlSession.close();
	}
}

4. UserDAOTest test classes:

package com.dayee;

import com.dayee.dao.UserDao;
import com.dayee.dao.UserDaoImpl;
import com.dayee.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class UserDaoTest {

	private SqlSessionFactory sqlSessionFactory;

	@Before
	public void init() throws Exception {
		// 创建SqlSessionFactoryBuilder
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
		// 加载SqlMapConfig.xml配置文件
		InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		// 创建SqlsessionFactory
		this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
	}

	@Test
	public void testQueryUserById() {
		// 创建DAO
		UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
		// 执行查询
		User user = userDao.queryUserById(1);
		System.out.println(user);
	}

	@Test
	public void testQueryUserByUsername() {
		// 创建DAO

		UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);
		// 执行查询
		List<User> list = userDao.queryUserByUsername("张");
		for (User user : list) {
			System.out.println(user);
		}
	}

	@Test
	public void testSaveUser() {
		// 创建DAO
		UserDao userDao = new UserDaoImpl(this.sqlSessionFactory);

		// 创建保存对象
		User user = new User();
		user.setUsername("刘备");
		user.setBirthday(new Date());
		user.setSex("1");
		user.setAddress("蜀国");
		// 执行保存
		userDao.saveUser(user);

		System.out.println(user);
	}
}

5. turn test, success.

 

6. The following problems in the development of the original Dao:

  1. Dao presence of duplicate code method: by creating SqlSession SqlSessionFactory, calling a method of operating a database of SqlSession
  2. Call sqlSession database operations need to specify the method id statement, there are hardcoded here, not maintenance in development.

 

 

4. Mapper dynamic proxy mode

4.1. Development Specification

Mapper interface development method only need to write the interface Mapper (corresponding Dao Interface) created by the dynamic proxy object interface Mybatis frame according to the interface definition, the same method of the top member of the proxy object class methods Dao interface.

 

Mapper interface development need to follow the following specifications:

  1. Namespace class path with the same mapper interface Mapper.xml file.
  2. Mapper same name and each interface methods defined in the statement of Mapper.xml id
  3. ParameterType same input parameters and type of each sql Mapper interface methods defined type mapper.xml
  4. The same type and output parameters of each resultType sql Mapper interface method of the type defined mapper.xml

 

1. Develop entity will generally corresponding mapper file in the resources / mapper directory, sqlmap right directory for demonstration use.

 

2. Edit UserMapper.xml mapping 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:命名空间,用于隔离sql,还有一个很重要的作用,使用动态代理开发DAO -->
<!-- 1. namespace必须和Mapper接口类路径一致 -->
<mapper namespace="com.dayee.mapper.UserMapper">

    <!-- 2. id必须和Mapper接口方法名一致 -->
    <!-- 3. parameterType必须和接口方法参数类型一致 -->
    <!-- 4. resultType必须和接口方法返回值类型一致 -->
    <!-- 根据id查询用户 -->
    <select id="queryUserById" parameterType="int" resultType="com.dayee.entity.User">
      select * from user where id = #{id}
   </select>

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

    <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.dayee.entity.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>

 

3.SqlMapConfig.xml files to load mapper file

<?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>
    <!-- 和spring整合后 environments配置将废除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理 -->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="123" />
            </dataSource>
        </environment>
    </environments>

    <!--加载映射文件-->
    <mappers>
        <!--<mapper resource="sqlmap/UserMapper.xml"/>-->
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

 

4.UserMapper Interface

package com.dayee.mapper;

import com.dayee.entity.User;

import java.util.List;

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. Test categories:

package com.dayee;

import com.dayee.entity.User;
import com.dayee.mapper.UserMapper;
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 org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class UserMapperTest {

	private SqlSessionFactory sqlSessionFactory;

	@Before
	public void init() throws Exception {
		// 创建SqlSessionFactoryBuilder
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
		// 加载SqlMapConfig.xml配置文件
		InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		// 创建SqlsessionFactory
		this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
	}

	@Test
	public void testQueryUserById() {
		// 获取sqlSession,和spring整合后由spring管理
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		// 从sqlSession中获取Mapper接口的代理对象
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		// 执行查询方法
		User user = userMapper.queryUserById(1);
		System.out.println(user);
		// 和spring整合后由spring管理
		sqlSession.close();
	}

	@Test
	public void testQueryUserByUsername() {
		// 获取sqlSession,和spring整合后由spring管理
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		// 从sqlSession中获取Mapper接口的代理对象
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		// 执行查询方法
		List<User> list = userMapper.queryUserByUsername("张");
		for (User user : list) {
			System.out.println(user);
		}
		// 和spring整合后由spring管理
		sqlSession.close();
	}

	@Test
	public void testSaveUser() {
		// 获取sqlSession,和spring整合后由spring管理
		SqlSession sqlSession = this.sqlSessionFactory.openSession();
		// 从sqlSession中获取Mapper接口的代理对象
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		// 创建保存对象
		User user = new User();
		user.setUsername("刘备");
		user.setBirthday(new Date());
		user.setSex("1");
		user.setAddress("蜀国");
		// 执行查询方法
		userMapper.saveUser(user);
		System.out.println(user);
		// 和spring整合后由spring管理
		sqlSession.commit();
		sqlSession.close();
	}
}

 

6. Click the test successfully.

 

4.2. Summary

1)selectOne和selectList

Dynamic proxy object calls sqlSession.selectOne () and sqlSession.selectList () is an interface method return value mapper decision, if the return list selectList method is called, if the method returns a single object selectOne the call.

2)namespace

mybatis official recommended mapper mapper interfaces proxy method development, programmers do not write mapper interface class, use mapper proxy method, input parameters can be used pojo wrapper objects or map objects, ensure versatility of dao.

 

 

5. Summary

Mapper interface development need to follow the following specifications:

  1. Namespace class path with the same mapper interface Mapper.xml file.
  2. Mapper same name and each interface methods defined in the statement of Mapper.xml id
  3. ParameterType same input parameters and type of each sql Mapper interface methods defined type mapper.xml
  4. The same type and output parameters of each resultType sql Mapper interface method of the type defined mapper.xml

 

Guess you like

Origin blog.csdn.net/xuruanshun/article/details/102701973