Gain insight into MyBatis return values
To understand the return value, we need to understand resultType , resultMap as well as the return value defined in the interface method.
Let's look first resultType andresultMap
Resulttype and Resultmap
Everyone should know that <select> there are two ways to set the return value in the MyBatis tab, respectively resultMap resultType .
resultMap resultType the code for processing and is as follows:
Private void Setstatementresultmap(String Resultmap, class<?> resulttype, ResultsetType ResultsetType, Mappedstatement.bu Ilder statementbuilder) {resultmap = Applycurrentnamespace (Resultmap,true); List<resultmap> Resultmaps =NewArraylist<resultmap> ();if(Resultmap! =NULL) {string[] Resultmapnames = Resultmap.split (","); for(String resultmapname:resultmapnames) {Try{Resultmaps.add (Configuration.getresultmap (Resultmapname.trim ())); }Catch(IllegalArgumentException e) {Throw NewIncompleteelementexception ("Could not find result map"+ Resultmapname, E); } } }Else if(Resulttype! =NULL) {Resultmap.builder Inlineresultmapbuilder =NewResultmap.builder (Configuration, statementbuilder.id () +"-inline", Resulttype,NewArraylist<resultmapping> (),NULL); Resultmaps.add (Inlineresultmapbuilder.build ()); } statementbuilder.resultmaps (Resultmaps); Statementbuilder.resultsettype (ResultsetType);}
You can see that this is resultMap a resultType priority, but it is also used .
Next look at MyBatis after getting the data, if you work with a single row of results (for example, in simple data, regardless of the nesting situation):
PrivateObjectGetrowvalue(Resultsetwrapper RSW, Resultmap resultmap)throwsSQLException {FinalResultloadermap Lazyloader =NewResultloadermap (); Object resultobject = Createresultobject (RSW, Resultmap, Lazyloader,NULL);if(Resultobject! =NULL&&!typehandlerregistry.hastypehandler (Resultmap.gettype ())) {FinalMetaObject metaobject = Configuration.newmetaobject (Resultobject);BooleanFoundvalues = Resultmap.getconstructorresultmappings (). Size () >0;if(Shouldapplyautomaticmappings (Resultmap,!) AutoMappingBehavior.NONE.equals (Configuration.getautomappingbehavior ()))) {foundvalues = applyautomaticmapping S (RSW, Resultmap, MetaObject,NULL) || Foundvalues; } foundvalues = Applypropertymappings (RSW, Resultmap, MetaObject, Lazyloader,NULL) || Foundvalues; Foundvalues = Lazyloader.size () >0|| Foundvalues; Resultobject = foundvalues? Resultobject:NULL;returnResultobject; }returnResultobject;}
The important code in the above code is as follows:
if (shouldApplyAutomaticMappings(resultMap, !AutoMappingBehavior.NONE.equals(configuration.getAutoMappingBehavior()))) { nullnull) || foundValues;
If it is determined whether the current support automatic mapping (can be configured), it is important, if not supported , then cannot use resultType the way, must use the resultMap way, if supported , resultType Way and resultMap Way can be used at the same time .
The basic logic here is to first resultMap assign a value to an attribute that does not have an automatic mapping, by applyAutomaticMappings implementing it.
If the object has resultMap , then the method is also done applyPropertyMappings .
That is, first process the field in the resultType auto-mapped field, in the processing resultMap of the configured fields, both can be used simultaneously!
Here are two ways to say it in order.
resultType Way
If auto-mapping is supported, then applyAutomaticMappings it executes, which has metaObject parameters.
final MetaObject metaObject = configuration.newMetaObject(resultObject);
Let's take metaObject a look at creating the most critical place in the Reflector class:
for (String propName : readablePropertyNames) { caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);}
Here, the attribute names in the entity are mapped, and the corresponding actual property names are capitalized. For example ID:id .
In applyAutomaticMappings the first row, you first get the column names that are not mapped:
final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
When you get the column name:
for (String columnName : columnNames) { final String upperColumnName = columnName.toUpperCase(Locale.ENGLISH); if (mappedColumns.contains(upperColumnName)) { mappedColumnNames.add(upperColumnName); else { unmappedColumnNames.add(columnName); }}
Note that the column names are converted to uppercase , and both the mapped and unmapped columns are saved mappedColumnNames unmappedColumnNames .
Because both the property name and the query column are uppercase, the column names and property names are matched as long as they are capitalized.
So when we write SQL, we don't need to convert the case of the query columns, and the auto-match is case-insensitive.
resultMap Way
This approach is also very simple, mentioned above mappedColumnNames , when judging whether the mapping column, the use of mappedColumns.contains(upperColumnName) judgment, mappedColumns is the mapping of our configuration column, that is not our configuration must be capitalized when it?
Not really, it's not case-sensitive, it's not case-sensitive, look at the <result column="xxx" ../> column following code:
for (ResultMapping compositeResultMapping : resultMapping.getComposites()) { final String compositeColumn = compositeResultMapping.getColumn(); ifnull) { resultMap.mappedColumns.add(compositeColumn.toUpperCase(Locale.ENGLISH)); }}
Here also converted to uppercase.
Here about resultTypt and the resultMap end, but there is a simple question, many people do not understand, what is it? Look at the next headline.
MyBatis Interface return value
The interface return value is usually a result, or an array List .
How does MyBatis know if I want to return a result or multiple results?
MapperMethodSome of the code in is as follows:
if (method.returnsVoid() && method.hasResultHandler()) { executeWithResultHandler(sqlSession, args); nullelseif (method.returnsMany()) { elseif (method.returnsMap()) { else { Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param);}
You can see that the results of the query are 4 in the case, void list (and array ), map , one .
The important thing here is if the judging condition, this judgment condition calculation method:
this.returnType = method.getReturnType();thisvoid.class.equals(this.returnType);this.returnsMany = (configuration.getObjectFactory().isCollection(thisthis.returnType.isArray());
As you can see, these conditions are entirely determined by the return value of the method. So if you write a return value that is an array or a collection, the result is multiple.
What happens if the return value itself has more than one, but the return value writes a Pojo, not a collection or an array?
The answer will be an error TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size()) .
Whether it is returning a result or multiple results, MyBatis is installing multiple results for querying, SelectOne is querying one, selectlist is querying multiple, let's see SelectOne Code:
public <T> T SelectOne (String statement, Object parameter) {list<t> List = this . < ; T>selectlist (statement, parameter); if (list.size () = = 1 ) {return list.get (0 ); } else if (List.size () > 1 ) {throw new toomanyresu Ltsexception ( "expected one result (or null) to being returned by SelectOne (), but found:" + List.size ()); } else {return nul L ; }}
Take a look:
this.<T>selectList(statement, parameter);
In fact, regardless of whether you query one or more results, MyBatis is queried by multiple results first. listafter getting the results in judgment.
If you are querying a result, you list can have at most one return value. Through the above code if else if esle can be very clear understanding.
resultTyp , resultMap and how much is the return value related?
There is no relationship.
Through the preceding resultType and resultMap the content, we should know that this property is to configure how the JDBC query results are mapped to an object.
Regardless of what the return value is or a few, the resultType results are returned by and resultMap generated.
The type of the returned result is determined by resultType and resultMap .
returns the type of the result
Return the type of the result resultType and resultMap decide, is not very surprised???
This is actually the case.
For instance, there is an entity Country and Country2 .
Interface List<Country> selectAll() , in XML <select id="selectAll" resultType="Country2"> .
What is the return value when you call through the interface? You think you're List in the object type Country , but they're actuallyCountry2
If the interface method is Country selectById(Integer id) , in XML <select id="selectById" resultType="Country2"> , because of the type inconsistency, the query will be error:java.lang.ClassCastException: xx.Country2 cannot be cast to xx.Country
why is that?
this is because the interface invocation method is the encapsulation of the namespace-mode invocation .
What is the type of the returned result when you call it by namespace mode?
It is easy to understand the types of decisions that are made by resultType and resultMap . But instead of the interface, it feels different.
This is because the interface method has more return values, so we would think that the return must be of this type. is actually wrong.
Special cases
When using pure annotation, the return value type of an interface can work, and if no annotation is used to specify the return value type @ResultType , then the return value type as written here is used resultType .
Gain insight into MyBatis return values