Mapper Agent (11)

Source: Internet
Author: User

OriginalDAODevelopment issues

1,theDAO Interface Implementation class method has a large number of template methods, it is envisaged that the code can be extracted, greatly reducing the workload of the programmer.

2. The ID of statement is hard-coded whencalling the sqlsession method

3 . the variable passed in when the Sqlsession method is called, because the sqlsession method uses generics, even if the variable type passes in the error (the generic class is passed in), In the compilation stage also does not have the error, is unfavorable to the programmer development.

MapperProxy methods (programmers only need toMapperinterface (equivalent toDAOinterface))

Ideas (mapper Agent Development Specification):

Mapper agent Development avoids a lot of duplicate code of the implementation class in the original DAO Interface Development, let the programmer lighten the workload

Delete, update, add operation for SQL statement will not take effect until the session is submitted

Programmers also need to write mapper.xml mapping files

Programmers writing Mapper interfaces need to follow some development specifications,mybatis can automatically generate mapper Interface implementation class proxy objects.

Development specification:

1. namespace equals mapper interface address in mapper.xml

2. The method name in the Mapper.java interface is consistent with the statement ID in the mapper.xml

( using the mapper proxy object,mybatis automatically finds the corresponding statement based on the interface address and namespace . ID)

3. method input parameter type inMapper.java interface and statement in mapper.xml ParameterType specifies the same type.

4. methods in the Mapper.java interface return value types and mapper.xml in statement of the Resulttype specifies the same type.

Proxy object Internal CallSelectOneorSelectList

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 .

Mapperinterface method parameters can only have one effect on system development

Mapper interface method parameters can only have one, whether the system is not conducive to extended maintenance.

In the system framework, theDAO Layer Code is common to the business layer.

Even if the mapper interface has only one parameter, the Pojo of the wrapper type can be used to meet the needs of different business methods.

Note: The parameters of the persistence layer method can be wrapped type,map... , the wrapper type is not recommended in the service method (it is not conducive to the extensibility of the business layer).

Structure of the Eclipse project

Usermapper.xml

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace namespace, the role of Death to classify the SQL management, understanding SQL Isolation Note: The use of Mapper proxy method development, namespace has a special role (just beginning to learn not to understand)-<MapperNamespace= "Ql.mybatis.mapper.UserMapper"><!--Configuring many SQL statements in a mapping file-<!--Requirements: Querying the records of user tables by ID-<!--Query ID to execute the database through select: SQL that identifies the mapping file encapsulates the SQL statement into the Mappedstatement object, so ID is called statement ID parametertype: Specifies the type of input parameter, specifying the int type #{ } represents a placeholder #{id}: Where the ID represents the parameter that accepts the input, the parameter name is the ID, and if the input argument is a simple type, the parameters in #{} can be arbitrarily Resulttype: Specifies the type of Java object that the result of the SQL output is mapped to. SELECT specifies Restulttype to map a single record into a Java object-<SelectId= "Finduserbyid"ParameterType= "int"Resulttype= "Ql.mybatis.pojo.User">SELECT * from User where Id=#{id}</Select><SelectId= "FindUserById2"ParameterType= "Ql.mybatis.pojo.User"Resulttype= "Ql.mybatis.pojo.User">SELECT * from User where sex=#{sex} and Address=#{address}</Select><!--Based on the user name fuzzy query user information, may return multiple Resulttype: Specifies that the single record is mapped by the Java object Type ${}: Represents the concatenation of the SQL string, the contents of the received parameters are not decorated with any adornment in SQL. Use ${} to stitch sql, causing SQL injection ${value}: Receive input parameter contents, if the incoming type is a simple type, ${} can only use the value-<SelectId= "Finduserbyname"ParameterType= "String"Resulttype= "Ql.mybatis.pojo.User">SELECT * from USER WHERE username like '%${value}% '</Select><!--Add User parametertype: Specifies that the input parameter type is Pojo (including user information) #{} Specifies the property name of the Pojo, receives the property value of the Pojo object, MyBatis gets the property value of the object by OGNL-<InsertId= "Insertuser"ParameterType= "Ql.mybatis.pojo.User">Insert into User (username,birthday,sex,address) value (#{username},#{birthday},#{sex},#{address})</Insert><!--Delete User-<DeleteId= "DeleteUser"ParameterType= "Java.lang.Integer">Delete from user where Id=#{id}</delete> <!-- Update the user must specify an ID, otherwise the contents of the table will be updated all --> <update id= " UpdateUser " Parametertype=" Ql.mybatis.pojo.User " Span style= "color: #0000ff;" >> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=# {address} where Id=#{id} </update></mapper>  

Usermapper Interface:

PackageQl.mybatis.mapper;ImportJava.util.List;ImportQl.mybatis.pojo.User;PublicInterfaceUsermapper {public User Finduserbyid (int ID) throws Exception; public list<user> finduserbyname (String name)  Exception; public user findUserById2 (user user) throws Exception; public void insertuser (user user) throws Exception; public void DeleteUser ( int ID) throws Exception;}       

Unit Test class:

PackageQl.mybatis.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;ImportQl.mybatis.mapper.UserMapper;ImportQl.mybatis.pojo.User;PublicClassusermappertest {sqlsession sqlsession =Null; @BeforePublicvoid SetUp ()ThrowsException {//MyBatis configuration file String resource = "Sqlmapconfig.xml";//Get configuration file stream InputStream InputStream =Resources.getresourceasstream (Resource);//Create a session factory, pass in MyBatis profile information sqlsessionfactory sqlsessionfactory =NewSqlsessionfactorybuilder (). Build (InputStream); Sqlsession =Sqlsessionfactory.opensession (); } @TestPublicvoid Testfinduserbyid ()ThrowsException {Usermapper usermapper = Sqlsession.getmapper (usermapper.Class); User user = Usermapper.finduserbyid (22); SYSTEM.OUT.PRINTLN (user); } @TestPublicvoid Testfinduserbyname ()ThrowsException {//Get the proxy object, interface callback Usermapper usermapper = Sqlsession.getmapper (usermapper.Class); list<user> list = Usermapper.finduserbyname ("Xiao Ming"); SYSTEM.OUT.PRINTLN (list); } @TestPublicvoid Testinsertuser ()ThrowsException {Usermapper usermapper = Sqlsession.getmapper (usermapper.Class); User User =NewUser (); User.setsex ("1"); User.setaddress ("Beijing"); User.setbirthday (NewDate ()); User.setusername ("Wang Dadong"); Usermapper.insertuser (user); Sqlsession.commit (); } @TestPublicvoid Testdeleteuser ()throws Exception {Usermapper Usermapper = Sqlsession.getmapper (Usermapper. Class); Usermapper.deleteuser (10public void testFindUserById2 () throws Exception {Usermapper usermapper = Sqlsession.getmapper (Usermapper.class); User User=new user (); User.setsex ("1" ); User.setaddress ("Fujian Fuzhou" usermapper.finduserbyid2 (user); System.out.println (User2); }}

You should also add the Sqlmapconfig.xml in the configuration file:

<Resource= "Mapper/usermapper.xml"/>  

Can see and do not write Usermapper interface implementation class, MyBatis help us to generate a mapper proxy object

Mapper Agent (11)

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.