How to develop Mybatis mapper agent

Source: Internet
Author: User

how 1.Mapper agents are developed

Using MyBatis to develop DAO, there are usually two methods, namely the original DAO development method and the Mapper interface development method. MyBatis in the development of DAO, it involves three sisters, namely Sqlsessionfactorybuilder, Sqlsessionfactroy, sqlsession.

Small partners know that the sqlsession in the operation of the database, such as: adding and removing changes, through sqlsessionfactory to create sqlsession, And Sqlsessionfactory is created through Sqlsessionfactorybuilder.

A, Sqlsessionfactorybuilder

Sqlsessionfactorybuilder is used to create sqlsessionfacoty,sqlsessionfacoty once created, no sqlsessionfactorybuilder is needed. Because Sqlsession is produced by Sqlsessionfactory, Sqlsessionfactorybuilder can be used as a tool class, and the best use range is the method scope, the method body local variables.

B, Sqlsessionfactory

Sqlsessionfactory is an interface that defines the different overloaded methods of opensession, the best use of sqlsessionfactory is the entire application run, once created can be reused, Sqlsessionfactory is usually managed in a singleton mode.

C, sqlsession

Sqlsession is a user-oriented interface that defines database operations in Sqlsession and uses Defaultsqlsession implementation classes by default.

There are many ways to manipulate databases in sqlsession: SelectOne (returning a single object), SelectList (returning single or multiple objects), sqlsession being thread insecure, In the Sqlsesion implementation class, in addition to the method in the interface (the method of manipulating the database) there are data domain properties, sqlsession the best application in the method body, defined as local variables used, you can never place a reference to the Sqlsession instance in a static field or instance field of a class. In today's blog post, the small series will focus on the small partners to introduce the two methods of developing DAO in MyBatis, the development Way of primitive DAO and the development of mapper agent.

The development method of DAO in MyBatis is the development of Primitive DAO and the development of mapper agent, the original DAO development and Mapper Dynamic agent development, both of which have advantages. Primitive DAO Development: Programmers need more code to write DAO and DAO implementations, but better understand. Mapper Dynamic Agent: Programmers only need to write Mapper interface, and then configure according to specifications, MyBatis will automatically implement similar DAO implementation, reduce the template method. MyBatis official recommend the use of Mapper proxy method to develop Mapper interface, programmers do not have to write Mapper interface implementation class, when using the Mapper proxy method, input parameters can use Pojo wrapper object or Map object, to ensure the universality of DAO.

Here mainly introduces the mapping agent development mode

2.Mybatis Development process

1, write the MyBatis configuration file Sqlmapconfig.xml

2, write MyBatis mapping file Mapper.xml

Here is the main definition of statement and SQL statements

3, programming through the configuration file to create Sqlsessionfactory

4. Get sqlsession through Sqlsessionfactory

5, through the sqlsession operation database

If you do add, update, delete, you need to call Sqlsession.commit ()

6. Sqlsesion use complete to close

3. Development Specification of mapper Agent

1. The fully qualified name of the Mapper interface is identical to the namespace value of the mapper mapping file.

Usermapper.xml

[Java]View PlainCopy 
    1. <?xmlversion= "1.0" encoding="UTF-8"?>
    2. <! Doctypemapper
    3. Public"-//mybatis.org//dtdmapper 3.0//en"
    4. "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    5. <!--namespace namespace, in order to isolate SQL statements, easy to manage, mapper develop DAO way, use namespace have special function
    6. Mapper agent is developed with namespace specified as the fully qualified name of the Mapper interface
    7. -
    8. <mapper namespace="Cn.itcast.mybatis.mapper.UserMapper" >

This step is intended to be associated with Mapper.xml and Mapper.java.

2. the ID of statement in Usermapper.xml is the method name in Mapper.java

3. The method parameter type of the Mapper interface is consistent with the ParameterType value of the statement of the mapper mapping file.

4. The method return value type of the Mapper interface is consistent with the Resulttype value of the statement of the mapper mapping file.



4. Development

"1" Mapping interface

[HTML]View PlainCopy 
    1. public interface usermapper{
    2. 1. Query user information based on user ID
    3. Public User Finduserbyid (int id) throws Exception;
    4. 2. Add Users
    5. public void Insertuser (user user) throws Exception;
    6. 3. Query user information according to user name
    7. Public List<User> Finduserbyname (String username) throws Exception;
    8. }

"2" Mapper mapping file

Create the Mapper directory under config and create the Usermapper.xml

The fully qualified name of the namespace and mapper interfaces is consistent

[Java]View PlainCopy 
  1. <mapper namespace="Cn.itcast.mybatis.mapper.UserMapper" >
  2. <!--query user information by ID
  3. ID: uniquely identifies a statement
  4. #{}: Represents a placeholder, if a parameter in a simple type is passed in #{}, the name in #{} is arbitrarily
  5. ParameterType: Type of input parameter, receive ParameterType input parameters via #{}
  6. Resulttype: Output type, regardless of whether the return is multiple or single, specifies the Pojo type of a single record map
  7. -
  8. <select id="Finduserbyid" parametertype="int" resulttype="Com.itheima.mybatis.po.user" >
  9. SELECT * from USER WHERE id= #{id}
  10. </select>
  11. <!--Add Users
  12. ParameterType: Type of input parameter, user object includes Username,birthday,sex,address
  13. #{} receives Pojo data, you can use OGNL to parse out the value of the Pojo property
  14. #{username} indicates that the property value of Pojo is obtained from the ParameterType
  15. Selectkey: Used for primary key return, defines the SQL that gets the primary key value
  16. Order: Sets the sequence of SQL execution in Selectkey, relative to the INSERT statement
  17. Keyproperty: Setting the primary key value to which property
  18. Result type of Resulttype:select last_insert_id ()
  19. -
  20. <insert id="Insertuser" parametertype="Cn.itcast.mybatis.po.User" >
  21. <selectkey keyproperty="id" order="after" resulttype="int" >
  22. Select LAST_INSERT_ID ()
  23. </selectKey>
  24. INSERT into USER (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address})
  25. </insert>
  26. <!--query user information based on user name, may return more than one
  27. ${}: Represents the concatenation of the SQL, through the ${} to receive parameters, the contents of the parameters without any decoration splicing in SQL.
  28. -
  29. <select id="finduserbyname" parametertype="java.lang.String" resulttype= "Cn.itcast.mybatis.po.User ">
  30. SELECT * from user where usernamelike '%${value}% '
  31. </select>
  32. </mapper>

"3" Load Map file

Load the Usermapper.xml in Sqlmapconfing.xml, and if you integrate with spring, you can use the Mapper scanner provided in the consolidation package, where the mappers is not configured. The code looks like this:

"4" Test code

Summary:

Proxy object Internal call SelectOne or SelectList

If the Mapper method returns a single Pojo object (not a collection object), the proxy object queries the database internally through SelectOne.

If the Mapper method returns a collection object, the proxy object internally queries the database through SelectList.

How to develop Mybatis mapper agent

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.