Dao Dao original development MyBatis development and the development of dynamic proxies Mapper

@
Use MyBatis develop Dao, usually there are two methods, namely Dao original development methodology and development Mapper dynamic proxy method. The following problems in the development of the original Dao:
Dao method for the presence of duplicate code: SqlSessionFactory created by SqlSession, call the database method of operation SqlSession

 call sqlSession method of operation of the database needs to be specified id statement, there are hardcoded here, not maintenance in development.

The dynamic development agency Mapper interface development method only requires programmers to write Mapper interfaces (equivalent Dao interfaces) by

Mybatis framework creates dynamic proxy object interface according to the interface definitions, methods of the proxy object the same upper body Dao interface class.

When using the method to develop dao mapper agents, programmers only need to do two things can be:

1, write mapper.xml mapping file
2, write mapper interfaces (equivalent dao Interface)

Mapper interface development requires the following four specifications (recommended for beginners understood in conjunction with the FIG.) :
1, and the same namespace class path mapper interface Mapper.xml file.
2, each statement of the name and the ID Mapper interface methods defined in the same Mapper.xml
3, each of the same type parameterType sql input parameter types and mapper.xml Mapper interface methods defined in
4, an output interface method parameters Mapper and the same type as each of the sql resultType defined mapper.xml

Ahem ... beginner text (Mapper interface development, four specifications) true bit strenuous, bloggers I can scrap it harder to do the following figure, easy to understand:

Here Insert Picture Description

Dao original development mode

Original development process requires programmers to write Dao Dao Dao interfaces and implementation classes.

1. Preparation of mapping file

Write mapping file as follows :( can also use the map file entry procedures completed)

<?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,还有一个很重要的作用,后面会讲 -->
<mapper namespace="test">

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

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

    <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.gx.mybatis.pojo.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. Write Dao Interface

Interface Development to carry out the DAO, coded as follows:

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. Write Dao implementation class

Written Dao implementation class as follows

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. Write Dao test

JUnit create a test class, for UserDao test (acting as the main method) test code is as follows:

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

Mapper dynamic proxy mode

1. Define Mapper.xml (mapping file)

UserMapper.xml mapper mapping file defines
the config UserMapper.xml placed under the directory mapper effect is as follows:
Here Insert Picture Description

2, write UserMapper.xml profile content:

<?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.gx.mybatis.mapper.UserMapper">
    <!-- 根据用户id查询用户 -->
    <!-- 2. id必须和Mapper接口方法名一致 -->
    <!-- 3. parameterType必须和接口方法参数类型一致 -->
    <!-- 4. resultType必须和接口方法返回值类型一致 -->
    <select id="queryUserById" parameterType="int"
        resultType="com.gx.mybatis.pojo.User">
        select * from user where id = #{id}
    </select>

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

    <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.gx.mybatis.pojo.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. Write UserMapper (interface file)

Creating UserMapper interface code as follows:

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

4. Load UserMapper.xml file

SqlMapConfig.xml modify the file, add the content shown below:

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

5. Preparation of test

Written tests:

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("2");
        user.setAddress("鼠国");
        // 执行查询方法
        userMapper.saveUser(user);
        System.out.println(user);


        // 和spring整合后由spring管理
        sqlSession.commit();
        sqlSession.close();
    }
}

If this article there is a little bit of help to you, then please point a chant praise, thank you ~

Finally, if there is insufficient or is not correct, please correct me criticism, grateful! If you have questions please leave a message, the absolute first time to reply!

I welcome you to focus on the public number, to explore technology, yearning technology, the pursuit of technology, said good pots Friends is coming Oh ...

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/yichunguo/p/11990961.html