Mybatis framework 3: dao layer development, Mapper dynamic proxy development, and mybatismapper

Source: Internet
Author: User

Mybatis framework 3: dao layer development, Mapper dynamic proxy development, and mybatismapper

Here is the most basic building: http://www.cnblogs.com/xuyiqing/p/8600888.html

Next we achieve a simple addition, deletion, modification, query: http://www.cnblogs.com/xuyiqing/p/8601506.html

 

However, it is found that the code is too repetitive.

Next we will integrate and implement DAO development:

 

I. Original DAO development:

package dao;import pojo.User;public interface UserDao {    public User selectUserById(Integer id);}
Package dao; import java. util. list; import org. apache. ibatis. session. sqlSession; import org. apache. ibatis. session. sqlSessionFactory; import pojo. user; public class UserDaoImpl implements UserDao {// inject private SqlSessionFactory sqlSessionFactory; public UserDaoImpl (SqlSessionFactory sqlSessionFactory) {this. sqlSessionFactory = sqlSessionFactory;} // query a User's public User selectUserById (Integer id) {SqlSession sqlSession = sqlSessionFactory by User id. openSession (); return sqlSession. selectOne ("test. findUserById ", id);} // you can use the User name to fuzzy query the public List <User> selectUserByUsername (Integer id) {SqlSession sqlSession = sqlSessionFactory. openSession (); return sqlSession. selectList ("test. findUserById ", id );}}

Test class:

package junit;import java.io.InputStream;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 dao.UserDao;import dao.UserDaoImpl;import pojo.User;public class DaoTest {    public SqlSessionFactory sqlSessionFactory;    @Before    public void before() throws Exception {        String resource = "sqlMapConfig.xml";        InputStream in = Resources.getResourceAsStream(resource);        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);    }    @Test    public void testDao() throws Exception {        UserDao userDao = new UserDaoImpl(sqlSessionFactory);        User user = userDao.selectUserById(10);        System.out.println(user);    }}

 

 

However, we still find code duplication and resource waste:

So I thought of Mapper dynamic proxy development:

Package mapper; import pojo. user; public interface UserMapper {// follow the four principles // interface method name = User. id name in xml // return value type and Mapper. the return value type in the xml file must be consistent // The input parameter type of the method and Mapper. the input parameter types in xml must be consistent. // bind the namespace to this interface. // if an object is returned, call the selectOne method. // If the input parameter type is List, call the selectlist method public User findUserById (Integer id );}

 

UserMapper. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- Write an SQL statement --> <mapper namespace = "mapper. UserMapper"> <! -- Query a user by ID --> <select id = "findUserById" parameterType = "Integer" resultType = "pojo. user "> select * from user where id =#{ v} </select> <! -- // Fuzzy query the user list by user name # {} select * from user where id =? Placeholder? = '5' $ {} select * from user where username like '% 5%' String concatenation --> <select id = "findUserByUsername" parameterType = "String" resultType = "pojo. user "> select * from user where username like" % "# {haha}" % "</select> <! -- Add user --> <insert id = "insertUser" parameterType = "pojo. user "> <selectKey keyProperty =" id "resultType =" Integer "order =" AFTER "> select LAST_INSERT_ID () </selectKey> insert into user (username, birthday, address, sex) values (# {username}, # {birthday}, # {address}, # {sex}) </insert> <! -- Update --> <update id = "updateUserById" parameterType = "pojo. user "> update user set username =#{ username}, sex =#{ sex}, birthday =#{ birthday }, address = # {address} where id = # {id} </update> <! -- Delete --> <delete id = "deleteUserById" parameterType = "Integer"> delete from user where id =#{ vvvvv} </delete> </mapper>

 

The main configuration file sqlMapConfig. xml:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <environments default="development">        <environment id="development">            <transactionManager type="JDBC" />            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver" />                <property name="url"                    value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />                <property name="username" value="root" />                <property name="password" value="xuyiqing" />            </dataSource>        </environment>    </environments>    <mappers>        <mapper resource="mapper/UserMapper.xml"/>     </mappers></configuration>

 

 

Test class:

Package junit; import java. io. inputStream; 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. test; import mapper. userMapper; import pojo. user; public class MybatisMapperTest {@ Test public void teid apper () throws Exception {String resource = "sqlMapConfig. xml "; InputStream in = Resources. getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). build (in); SqlSession sqlSession = sqlSessionFactory. openSession (); // SqlSession automatically generates an implementation class UserMapper userMapper = sqlSession for the interface. getMapper (UserMapper. class); User user = userMapper. findUserById (10); System. out. println (user );}}

 

 

We recommend that you use Mapper for dynamic proxy development.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.