Mapper interface of Mybatis-dao layer development

Source: Internet
Author: User

Mapper interface development method only requires programmers to write the Mapper interface (equivalent to DAO interface), the MyBatis framework creates an interface based on the interface definition of the dynamic proxy object, the proxy object's method body with the upper DAO interface implementation class method.

Mapper interface development is subject to the following specifications:

1. The namespace in the Mapper.xml file is the same as the classpath of the Mapper interface .

2. The Mapper interface method name is the same as the ID of each statement defined in the Mapper.xml

3. The input parameter type of the Mapper interface method is the same as the type of parametertype for each SQL defined in Mapper.xml

4. The output parameter type of the Mapper interface method is the same as the type of resulttype for each SQL defined in Mapper.xml

1. Mapper Mapping File

To define the mapper mapping file Usermapper.xml (content same as Users.xml), you need to modify the namespace value to the Usermapper interface path. Place the Usermapper.xml under the Mapper directory under Classpath.

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <!--namespaces, classifying and managing SQL (SQL Isolation) -<Mappernamespace= "com.sw.mapper.UserMapper">    <!--to configure SQL statements in a mapping file -    <!--The query is executed through SELECT, ID is used to identify the SQL (Statement-id) in the mapping file to encapsulate the SQL statement into Mappedstatement #{} represents the placeholder parametertype-the specified input parameter    The type of the number #{id}-id represents the input parameter , the parameter name is the ID, and if the input parameter is a simple type,the parameters in #{} can be arbitrarily  resulttype-Specifies the type of Java object to which the SQL output results are mapped -    <!--querying the records of user tables by ID -    <SelectID= "Finduserbyid"ParameterType= "int"Resulttype= "Com.sw.po.User">Select *from user where Id=#{id}</Select>        <!--Fuzzy query user information based on user name -    <!--resulttype-Specifies the object type mapped by a single record ${} splicing the SQL string, receiving the contents of the parameter , without any modification, splicing in SQL (there is an SQL vulnerability)  ${} receive input parameters,  If the incoming type is a simple type,only the value is used in ${}       -    <SelectID= "Finduserbyname"ParameterType= "Java.lang.String"Resulttype= "Com.sw.po.User">SELECT *from USER WHERE username like '%${value}% '</Select>        <!--Add User -    <!--specifies that the input parameter type is Pojo (including user information) #{} Specifies the Pojo property name , receives the Pojo property value MyBatis Gets the property value of the object by OGNL -    <InsertID= "Insertuser"ParameterType= "Com.sw.po.User">        <!--Gets the newly added record primary key return ID to the Poio object (User)SELECT last_insert_id (): Gets the primary key value that was just inserted into the record, only applies to the self-increment primary key  
     
      Keyproperty: Set the query to the primary key value to parametertype the specified object user inside the property to do ID, here is: ID,
                  -        <SelectkeyKeyproperty= "id"Order= "after"Resulttype= "Java.lang.Integer">SELECT last_insert_id () </Selectkey>INSERT into USER (id,username,birthday,sex,address) VALUES (#{id},#{username},#{birthday},#{sex},#{address}) <!--use the MySQL UUID to generate the primary key to return to the execution process: first to get the primary key through the UUID, and then set the primary key to the id attribute, followed by the inster execution of the user object from the The attribute value of the out ID -       <!--   
<selectkey keyproperty= "id" order= "before" resulttype= "java.lang.String" > Select UUID () & Lt;/selectkey> INSERT into USER (id,username,birthday,sex,address) VALUES (#{id},#{username},#{birthday},#{sex},# {address})
- </Insert> <!--Delete a user by ID - <DeleteID= "DeleteUser"ParameterType= "Java.lang.Integer">DELETE from USER WHERE Id=#{id}</Delete> <!--update the user's incoming user ID and related update information based on ID #{id}: Gets the user's property value from the input user object - <UpdateID= "UpdateUser"ParameterType= "Com.sw.po.User">UPDATE USER SET username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} WHERE Id=#{id} </Update></Mapper>
2. mapper.java-Interface File

The Mapper interface definition has the following characteristics:

1. The Mapper interface method name is the same as the statement ID defined in Mapper.xml (usermapper.xml)

2. The input parameter type of the Mapper interface method is the same as the ParameterType type of statement defined in Mapper.xml (user.xml)

3. The output parameter type of the Mapper interface method is the same as the Resulttype type of the statement defined in the Mapper.xml

The code is as follows:

 PackageCom.sw.mapper;Importjava.util.List;ImportCom.sw.po.User;/** @Author swxctx * @time December 1, 2016 * @Explain: Using Mapper Interface (user management), equivalent to DAO interface*/ Public InterfaceUsermapper {//querying users ' information by ID     PublicUser Finduserbyid (intIdthrowsException; //View user list by user name     Public list<user>Finduserbyname (String username)throwsException; //Add User     Public voidInsertuser (user user)throwsException; //Delete User     Public voidDeleteUser (intIdthrowsException;}

3. Test class

 Packagecom.sw.mapper.test;ImportJava.io.InputStream;Importjava.util.Date;Importjava.util.List;Importorg.apache.ibatis.io.Resources;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder;ImportOrg.junit.Before;Importorg.junit.Test;ImportCom.sw.mapper.UserMapper;ImportCom.sw.po.User;/** @Author swxctx * @time December 1, 2016 * @Explain:*/ Public classUsermappertest {Privatesqlsessionfactory sqlsessionfactory; @Before Public voidSetupbefore ()throwsException {//need to create sqlsessionfactory before executing other methods//mybatis configuration fileString resource = "Sqlmapconfig.xml"; //get configuration file streamInputStream InputStream =Resources.getresourceasstream (Resource); //creating a session factory, passing in MyBatis profile informationSqlsessionfactory =NewSqlsessionfactorybuilder (). Build (InputStream); } @Test Public voidTestfinduserbyid ()throwsexception{sqlsession sqlsession=sqlsessionfactory.opensession (); //Create Usermapper object, MyBatis automatically generate Mapper proxy objectUsermapper usermapper = Sqlsession.getmapper (usermapper.class); //calling the Usermapper methodUser user = Usermapper.finduserbyid (27);                Sqlsession.close ();    SYSTEM.OUT.PRINTLN (user); } @Test Public voidTestfinduserbyname ()throwsexception{sqlsession sqlsession=sqlsessionfactory.opensession (); //Create Usermapper object, MyBatis automatically generate Mapper proxy objectUsermapper usermapper = Sqlsession.getmapper (usermapper.class); //calling the Usermapper methodlist<user> User = Usermapper.finduserbyname ("King");                Sqlsession.close ();    SYSTEM.OUT.PRINTLN (user); } @Test Public voidTestinsertuser ()throwsexception{sqlsession sqlsession=sqlsessionfactory.opensession (); //Create UsermapperUsermapper usermapper = Sqlsession.getmapper (usermapper.class); User User=NewUser (); User.setusername ("Li Xiao"); User.setsex ("1"); User.setbirthday (NewDate ()); User.setaddress (Guangzhou); //Calling Methodsusermapper.insertuser (user); //Commit a transactionSqlsession.commit (); //Freeing ResourcesSqlsession.close (); } @Test Public voidTestdeleteuser ()throwsexception{sqlsession sqlsession=sqlsessionfactory.opensession (); //Create Usermapper object, MyBatis automatically generate Mapper proxy objectUsermapper usermapper = Sqlsession.getmapper (usermapper.class); //calling the Usermapper methodUsermapper.deleteuser (44);        Sqlsession.commit ();    Sqlsession.close (); }}

Note:

SelectOne and SelectList

The dynamic proxy object calls Sqlsession.selectone () and sqlsession.selectlist () are determined by the return value of the Mapper interface method, and the SelectList method is called if a list is returned. If a single object is returned, the SelectOne method is called.

Namespace

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.

Mapper interface of Mybatis-dao layer development

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.