This document address: How to develop your own general mapper
Blog layout than directly on the Gitosc view, suggest to go to the above link to view.
Objective
Since the release of the general Mapper-0.1.0 version, I feel that for a few people, this may be a tool they just need. At least in the current generic DAO, there are few more powerful than this.
But for others, using the MyBatis code generator (which I'm working with some friends to translate this document, address: MyBatis Generator) makes it easy to generate XML without using generic mapper.
In fact, if you can't pull out a generic single table in your own business (multiple tables can actually be implemented, but the limit will increase, rather than the handwritten XML) operation, the generic mapper has no particular advantage in addition to increasing your initial efficiency and cleaner XML configuration.
To make it easier to extend the generic mapper, I reconstructed version 0.1.0. The 0.2.0 version has been released, and here is how to develop the generic mapper that you need.
How to develop your own universal mapperRequirements
-
The generic mapper that you define must contain generics, for example MysqlMapper<T> .
-
The methods in the custom universal Mapper interface need to have the appropriate annotations. For details, refer toMapper
-
Inheritance MapperTemplate is required to implement specific methods of operation.
-
Annotations of a class in general mapper Provider can only use the same type type (this type is the third class to be implemented). )。 Actually method , it's all written as well.
Hsqldbmapper instancesThe first step is to createHsqldbMapper<T>
Public interface Hsqldbmapper<t> {}
This interface is the generic mapper that we define, and the specific interface method is written in the third step . Other mapper can inherit this HsqldbMapper<T> .
Part II, creatingHsqldbProvider
public class Hsqldbprovider extends Mappertemplate { //method of inheriting parent class public Hsqldbprovider (class<?> Mapperclass, Mapperhelper mapperhelper) { super (Mapperclass, mapperhelper); }}
This class is the actual processing operation of the class, need to inherit MapperTemplate , the specific code is written in the fourth step .
The third step, inHsqldbMapper<T>Add a common method in
Here's an example of a paged query.
Public interface Hsqldbmapper<t> { /** * Single-table paging query * * @param object * @param offset * @ param limit * @return * /@SelectProvider (Type=hsqldbprovider.class,method = "Dynamicsql") List <T> Selectpage (@Param ("entity") T object, @Param ("offset") int offset, @Param ("limit") int limit);}
The returned results are list, and the entry parameters are the query condition and the paging parameter, respectively. In the Mapper interface method, it is recommended to add annotations when there are multiple arguments @Param , otherwise it is necessary param1,param2... to reference the parameters.
You must also add annotations on the method. Query use, SelectProvider Insert use, @InsertProvider Update use UpdateProvider , delete use DeleteProvider . Different provider are equivalent to different nodes in XML, such as <select>,<insert>,<update>,<delete> .
Because here is the query, so to set to SelectProvider , these 4 Provider parameters are the same, only type and method .
typeMust be set to the actual execution method HasqldbProvider.class and method must be set to "dynamicSQL" .
While the General mapper processing is based on the type reflection HasqldbProvider lookup method, the processing mechanism of the mybatis requires that method must be type the only one entry in the class, and the return value is String . "dynamicSQL"method definition in MapperTemplate , the method is as follows:
Public String Dynamicsql (Object record) { return "Dynamicsql";}
This method is only to meet the requirements of mybatis, without any practical effect.
The fourth step, inHsqldbProviderTo implement a real SQL-handling approach in
One of the requirements here is that the HsqldbProvider HsqldbMapper<T> method name must be the same when dealing with the method, because it requires reflection to get the corresponding method, and the method name is consistent on the one hand to reduce the developer's configuration, on the other hand, and the interface will look clearer.
In addition to the method name must be the same, the entry parameter must be, in addition to the MappedStatement ms return value can be void or SqlNode one.
Here, let's talk about the principle of general mapper implementation. General Mapper is currently using interceptors to modify the properties of an object when the generic method is first executed MappedStatement SqlSource . And will only be executed once, and then it will be no different from the normal method.
Using Provider This mapper method of annotations, the MyBatis itself is processed into ProviderSqlSource (an SqlSource implementation Class), and because of the previous configuration, this ProviderSqlSource kind of SQL is returned in the code above "dynamicSQL" . This SQL has no effect, and if you do not make any changes, executing this code will definitely make a mistake. Therefore, in the interceptor to intercept the conforming interface method, encountered ProviderSqlSource by the reflection call as HsqldbProvider in the specific code to modify the original SqlSource .
What is the simplest way to deal with MyBatis SQL? is to create SqlNode , use DynamicSqlSource , in which case we do not need to process the arguments, and do not need to handle the various types of parameter mappings in the code. is much easier than the way SQL is executed.
About this part of the content is recommended to see the common Mapper source code and MyBatis source Understanding, if you do not know how to say more here but will be messy.
The following HsqldbProvider methods are added in public SqlNode selectPage(MappedStatement ms) :
/** * Paging Query * @param ms * @return */public sqlnode selectpage (mappedstatement ms) {class<?> Entityclass = Getsele Ctreturntype (MS); Modify the return value type to entity type Setresulttype (MS, Entityclass); list<sqlnode> sqlnodes = new arraylist<sqlnode> (); Static SQL section: Select column ... from table Sqlnodes.add (New Statictextsqlnode ("select" + Entityhelper.getselec Tcolumns (Entityclass) + "from" + TableName (entityclass)); Get all columns list<entityhelper.entitycolumn> columnlist = Entityhelper.getcolumns (Entityclass); list<sqlnode> ifnodes = new arraylist<sqlnode> (); Boolean first = true; For all column loops, generate <if test= "Property!=null" >[and] column = #{property}</if> for (entityhelper.entitycolumn column:columnlist) {Statictextsqlnode Columnnode = new Statictextsqlnode (first? "": "and") + column.getcolumn () + "= #{entity." + column.getproperty () + "}");if (Column.getjavatype (). Equals (String.class)) {Ifnodes.add (new Ifsqlnode (Columnnode, "entity.") +column.getproperty () + "! = null and" + "entity." +column.getproperty () + "! ="); } else {Ifnodes.add (new Ifsqlnode (Columnnode, "entity.") +column.getproperty () + "= null")); } first = false; }//Add if to <where> Sqlnodes.add (new Wheresqlnode (Ms.getconfiguration (), New Mixedsqlnode (Ifnodes))); Processing paging Sqlnodes.add (new Ifsqlnode (New Statictextsqlnode ("LIMIT #{limit}"), "offset==0"); Sqlnodes.add (New Ifsqlnode (New Statictextsqlnode ("LIMIT #{limit} OFFSET #{offset}"), "offset>0"); return new Mixedsqlnode (sqlnodes);}
Note: This code is difficult to find, you can compare the structure of the bottom of this page in the form of XML view.
First of all, this code is to implement the function, according to the input entity class parameters not equal to null (the string is not equal to ") of the property as the query criteria to query, according to the paging parameters paging.
First look at these two lines of code:
Gets the entity type class<?> Entityclass = Getselectreturntype (ms);//Modify the return value type to the entity type Setresulttype (MS, Entityclass);
The entity type is obtained first, and then setResultType is equivalent by changing the return value type to Entityclass resultType=entityClass .
Why do you want to change it here? because the default return value is T , Java is not automatically processed into our entity classes, by default Object , we need to manually set the return value type for all queries.
The insert,update,delete return value for these operations is all int , so you do not need to modify the return result type.
The SQL is then spelled out from the List<SqlNode> sqlNodes = new ArrayList<SqlNode>(); code, first the Select query header, and the EntityHelper.getSelectColumns(entityClass) alias is handled in.
Then get all the columns and create the nodes on the column loop <if entity.property!=null>column = #{entity.property}</if> . Finally, the list of these if nodes is placed <where> in a node.
This section uses the attribute entity. + 属性名 , where does it entity come from? From the annotations at the interface definition in front of us Param("entity") , the next two paging parameters are also. If you've ever used MyBatis, believe you can understand.
The paging <where> parameter is then added after the node, when offset==0 the paging code is different when and when offset>0 .
Finally encapsulated into a MixedSqlNode return.
Return after the general mapper is how to deal with, here paste the source:
Sqlnode Sqlnode = (sqlnode) Method.invoke (this, MS);D Ynamicsqlsource dynamicsqlsource = new Dynamicsqlsource ( Ms.getconfiguration (), Sqlnode); Setsqlsource (MS, Dynamicsqlsource);
Returned SqlNode after the creation DynamicSqlSource , and then modified the original Ms SqlSource .
Fifth step, configure the Universal Mapper interface to the interceptor plug-in
<plugins> <plugin interceptor= "Com.github.abel533.mapper.MapperInterceptor" > <!--================ ================================--> <!--configurable parameter descriptions (generally without modification)-<!--================================= ===============--> <!--UUID Generation policy-<!--configuring UUID generation policies requires the use of OGNL expression--<!--default 32-bit length: @[emai L protected] (). toString (). Replace ("-", "")-<!--<property name= "UUID" value= "@[email protecte D] (). toString () "/>--> <!--primary Key auto-write method, default MySQL, detailed description See document--<property name=" IDENTITY "value=" HSQL DB "/> <!--get rules for sequence, use {num} to format parameters, default = {0}.nextval, 3 for oracle--> <!--optional parameters, corresponding to 0,1,2, respectively Sequencename, columnname,propertyname--> <property name= "Seqformat" value= "{0}.nextval"/> <!--primary key self-increment write method execution order, default a fter, the optional value is (before| After)-<!--<property name= "ORDER" value= "after"/>--> <!--entity classes that support the map type, automatically convert the uppercase underlined key to camel-- <!--This processing makes the universal mapPer can support the entity of map type (the field in the entity must be defined as usual, otherwise it cannot be reflected)-<property name= "Camehumpmap" value= "true"/> <!--Universal Mapper interface, multiple commas--<property name= "mappers" value= "Com.github.abel533.mapper.Mapper, Com.github.abel533.hsqldb.HsqldbMapper "/> </plugin></plugins>
Here are the main mappers parameters:
<property name= "mappers" value= "Com.github.abel533.mapper.mapper,com.github.abel533.hsqldb.hsqldbmapper"/>
Multiple generic mapper can be separated by commas.
Test
Next, write the code to test.
Public interface Countrymapper extends mapper<country>,hsqldbmapper<country> {}
CountryMapperincrease the inheritance on HsqldbMapper<Country> .
Write the following tests:
@Testpublic void Testdynamicselectpage () { sqlsession sqlsession = mybatishelper.getsqlsession (); try { Countrymapper mapper = Sqlsession.getmapper (countrymapper.class); Paged query with query criteria country country = new country (); Country.setcountrycode ("US"); list<country> countrylist = mapper.selectpage (country, 0, ten); Total Queries assert.assertequals (1, countrylist.size ()); Null parameter query countrylist = mapper.selectpage (New country (), (); Assert.assertequals (Ten, Countrylist.size ()); } finally { sqlsession.close (); }}
The test output logs are as follows:
DEBUG [main]-==> preparing:select id,countryname,countrycode from country WHERE CountryCode =? LIMIT? DEBUG [main]-==> parameters:us (String), ten (Integer) TRACE [main]-<== columns:id, CountryName, Countrycodetra CE [main]-<== row:174, states of America, Usdebug [main]-<== total:1debug [main]-==> Preparing:select Id,countryname,countrycode from country LIMIT? OFFSET? DEBUG [main]-==> parameters:10 (integer), (integer) TRACE [main]-<== columns:id, CountryName, Countrycodet RACE [main]-<== row:101, Maldives, Mvtrace [main]-<== row:102, Mali, Mltrace [main]-<== row:103, Malta, Mttrace [main]-<== row:104, Mauritius, Mutrace [main]-<== row:105, Mexico, Mxtrace [main]-<== row:106, Moldova, Republic of, mdtrace [main]-<== row:107, Monaco, Mctrace [m Ain]-<== row:108, Mongolia, Mntrace [main]-<== row:109,Montserrat is, mstrace [main]-<== row:110, Morocco, Madebug [main]-<== total:10
The test does not have any problems.
Here's a bit of a feature that's easy to implement. In the code above:
Countrylist = Mapper.selectpage (New country (), 100, 10);
All results are queried when passing in a property that does not have any properties set Country . Some people think that passing in an empty object is better than passing in one null . We modify the test code to see the results.
Throws an exception after executing the test code:
caused by:org.apache.ibatis.ognl.OgnlException:source is null for getProperty (NULL, "id")
Why is it unusual, because the direct reference in our code above is entity.property not judged before the reference, entity != null thus causing the problem here.
We modify the HsqldbProvider method in the selectPage last few lines of code to modify the original code:
Add if to <where>sqlnodes.add (new Wheresqlnode (Ms.getconfiguration (), New Mixedsqlnode (Ifnodes)));
After modification:
Increase Entity!=null judgment Ifsqlnode Ifsqlnode = new Ifsqlnode (new Mixedsqlnode (Ifnodes), "Entity!=null");//Add if to <where >sqlnodes.add (New Wheresqlnode (Ms.getconfiguration (), Ifsqlnode));
Then the test will be no problem.
More examples
More examples can be found in the general mapper Mapper<T> and MapperProvider for reference purposes. The amount of code is not very large but it implements the commonly used features.
When you understand the principle and the structure you have mastered SqlNode , I believe you can write more and more powerful universal mapper.
I once said that I would write some generic mapper based on different databases, and when I started thinking about refactoring, I thought I should teach the developers who need the plugin how to implement it themselves.
A person's ability is limited, and write a thing open source for everyone to use very easy, but maintenance is not easy. So, I would like to think that this document is useful for you to share your own implementation.
Personally, if I have the time, I will consider adding generic Example queries. The Example design of the class is complex and the corresponding SqlNode structure is not very complex. If someone is interested, I can help develop Example generic queries.
Structure
For developers who have just learned about the above, it SqlNode may not be that intuitive, for ease of understanding. I am here to write the last modified Sqlnode in XML form.
<select id= "Selectpage" resulttype= "Com.github.abel533.model.Country" > select Id,countryname, CountryCode from country <where> <if test= "entity!=null> <if test=" Entity.id!=null "> id = #{entity.id} </if> <if test= "Entity.countryname!=null and entity.countryname!=" "> countryname = #{entity.countryname} </if> <if test= "Entity.countrycode!=null and Entity.countrycode!= ' "> countrycode = #{entity.countrycode} </if> </if> < /where> <if test= "offset==0" > LIMIT #{limit} </if> <if test= "Offset>0" > LIMIT #{limit} OFFSET #{offset} </if></select>
See this structure, and then the above code one by one corresponding should not be difficult to understand. Once you're familiar with it, you might also find it much easier to handle generic mapper in Java code mode.
teaches you how to develop MyBatis's universal mapper