mybatis xml configuration file configuration resultMap

 constructor - used when the class is instantiated, the result is injected into the constructor
        idArg - ID parameter; as a result of the ID tag may help improve overall performance
        arg - is injected into a normal result constructor
    id - an ID result; as a result of the ID tag can help improve the overall performance
    result - is injected into a field or JavaBean property Common results
    association - association of a complex type; many of the results of this type of packaging into
        nested result mappings - association may be specified as an element resultMap , or a reference
    collection - collection of a complex type
        nested result mappings - set may be specified as a resultMap element, or a reference to a
    discriminator - use the resulting value used to determine which resultMap
        case - mapping based on a result of some value
            nested result mappings - a case is a mapping result itself, and therefore may contain many of the same elements, or it can refer to an external resultMap.

ResultMap list of attributes Attribute Description
id current namespace a unique identifier for identifying a result map.
Fully qualified class name of the type or a type alias (aliases can be built above with reference to the table).
autoMapping If this property, MyBatis will open or close automatically mapped to the ResultMap. This property will override the global property autoMappingBehavior. The default value is: unset.

Best practice should take one step to establish the results of the mapping. Unit testing may play a significant help in this process. If you attempt to create a map like a huge result as the above example, then it may be wrong and difficult to use it to complete the work. From the most simple form, and gradually evolve. And do not forget unit testing! The disadvantages of using frames is that sometimes they look like a black box (regardless of whether the source code is visible). To ensure that you achieve the desired behavior and consistent, the best option is to write unit tests. When submitting bug it can also play a significant role.

The next section will be described in detail for each element.
& Result ID

<Property ID = "ID" column = "the post_id" />
<Property Result = "Subject" column = "post_subject" />

These maps are the result of the basic content. value id and the result will be a simple one column to the data type (string, integer, double precision floating point, date, etc.) property or field.

The only difference between the two is that id will be identified properties of an object, which will be used when comparing object instances. This improves overall performance, especially caching and nested result mapping (ie join mapping) time.

Element has two attributes:
Attribute Description Id and Result of
property or properties of the column is mapped to a field results. If JavaBeans properties to match the given name exists, then it will be used. Otherwise, MyBatis will look for property in the field of a given names. In either case, you can have complex property navigation using the usual dot-separated format. For example, you can map to something simple: "username", or mapped to some complex things: "address.street.number".
Column name column in the database, or column alias. In general, this parameter and resultSet.getString (columnName) as passed to the method.
javaType a fully qualified Java class name, alias, or a type (see above list of built-in type aliases). If you're mapping to a JavaBean, MyBatis can usually figure out the type. However, if you are mapping to a HashMap, then you should explicitly specify javaType to ensure the desired behavior.
jdbcType JDBC type, supported JDBC type See the table following "Supported JDBC type." You may only need to insert, update and delete allow null values in the column specified JDBC type. This is a JDBC requirement rather than MyBatis requirements. If you direct JDBC-oriented programming, you need to specify the type null value possible.
typeHandler default type of processor we discussed earlier. Using this property, you can override the default type of processor. The value is the fully qualified name of a class type processors, or a type alias.
Supported JDBC types

for future reference, MyBatis JDBC type by jdbcType enumeration included support below.
CHAR TIMESTAMP FLOAT OTHER UNDEFINED the BIT
TINYINT the BLOB BINARY VARCHAR NVARCHAR REAL
SMALLINT DOUBLE VARBINARY the CLOB a LONGVARCHAR the NCHAR
INTEGER BOOLEAN NCLOB a LONGVARBINARY the NUMERIC DATE
BIGINT DECIMAL NULL CURSOR the TIME ARRAY
constructor

by modifying the object attributes manner, sufficient for most data transmission target (Data Transfer Object, DTO) and the requirements of the vast majority of the domain model. But in some cases you want to use immutable class. Generally speaking, rarely or never changes, including a reference table or query data, they are suitable to use immutable classes. Constructor injection class allows you to set the attribute values at initialization, without exposing public methods. MyBatis also supports private properties and private JavaBeans properties to achieve this, but some people prefer Constructor injection. constructor element is born to do this.

Consider the following constructor:

public class the User {
   // ...
   the User public (ID Integer, String username, int Age) {
     // ...
  }
// ...
}

in order to inject the result constructor, MyBatis need to locate the appropriate method of construction in some way. In the example below, to search for a MyBatis declared constructor parameter is three, in order java.lang.Integer, java.lang.String and int arrangement.

<constructor>
   <idArg column = "ID" the javaType = "int" />
   <Arg column = "username" the javaType = "String" />
   <Arg column = "Age" the javaType = "_ int" />
</ constructor>

when you, error-prone in the correct order to ensure arg elements in processing a constructor parameter having a plurality of. Starting with version 3.4.3, may, subject to the specified parameter name, in any order written arg elements. In order to reference the constructor parameter by name, you can add @Param notes, or use the '-parameters' compilation options and enable useActualParamName option (enabled by default) to build the project. The following example is still the same construction method is effective, although the second order and third order parameter declared in the constructor for the mismatch.

<constructor>

   <Arg column = "Age" the javaType = "_ int" name = "Age" />
   <Arg column = "username" the javaType = "String" name = "username" />
</ constructor>

If the name and type of presence classes same the property, you can javaType omitted.

The remaining properties and rules and common element id and the result is the same.
Attribute describes the
column names in the database column, or column aliases. In general, this parameter and resultSet.getString (columnName) as passed to the method.
javaType a fully qualified Java class name, alias, or a type (see above list of built-in type aliases). If you're mapping to a JavaBean, MyBatis can usually figure out the type. However, if you are mapping to a HashMap, then you should explicitly specify javaType to ensure the desired behavior.
jdbcType JDBC type, supported JDBC type See "Supported JDBC type" Before this form. You may only need to insert, update and delete allow null values in the column specified JDBC type. This is a JDBC requirement rather than MyBatis requirements. If you direct JDBC-oriented programming, you need to specify the type null value possible.
typeHandler default type of processor we discussed earlier. Using this property You can override the default type of processor. The value is the fully qualified name of a class type processors, or a type alias.
ID select statement for mapping the complex property loading, the column it will retrieve the data from the column specified attribute, passed to the select statement as a parameter. For details, please refer Association label.
resultMap ResultMap the ID, it can be nested result set mapping to a suitable object tree, select functions and properties similar to the maps it can achieve multi-table join operation results into a single ResultSet. Such ResultSet will contain the results of the duplicate or partially duplicate sets of data are mapped to the correct nested object tree. To accomplish this, MyBatis allows you to "tandem" ResultMap, in order to solve the problem of nested results. For more information, please refer to the following elements of the Association.
constructor parameter name name. From the 3.4.3 version, by specifying a specific name, you can write arg elements in any order. See above explanation.
Associated

<Association Property = "author" column = "blog_author_id" the javaType = "the Author">
  <ID Property = "ID" column = "the author_id" />
  <Result Property = "username" column = "author_username" />
</ Association >

the association element deals "have a" relationship type. For example, in our example, a user has a blog. An association mapping works like any other result. You specify the target property to obtain the column values,

Different association is that you need to tell MyBatis how to load the association. MyBatis in this regard there will be two different ways:

    Nested Select: By executing another mapped SQL statement that returns the complex type desired.
    Nested Results: By using nested result mapping to process a subset of the combined duplicate results. First of all, then let us examine the properties of the element. All you will see, it is only by a select and ordinary and

mapping results resultMap attributes.
Attribute Description
property map the column result field or property. If JavaBeans properties to match the given name exists, then it will be used. Otherwise, MyBatis will look for the same given name field. In both cases you can use the usual dot complex property navigation. For example, you can map to something: "username", or mapped to some complex things: "address.street.number".
javaType a fully qualified Java class name, alias, or a type (see above list of built-in type aliases). If you're mapping to a JavaBean, MyBatis can usually figure out the type. However, as javaType if you are mapping to a HashMap, then you should explicitly specify javaType to ensure the desired behavior.
jdbcType type before this form of supported JDBC type list. JDBC type is only required to insert, update and delete operations may be processed into empty columns. This is a JDBC requirement, jdbcType not an MyBatis. Directly if you use the JDBC programming, you'll need to specify this type - but just might be empty-value pairs.
typeHandler We discussed default type handlers previously. Using this property, you can override the default typeHandler type of processor. The value is the fully qualified name of the class or type of a processor is implemented, or a type alias.
Associated nested query
attribute Describes
column column names from the database, or rename column labels. This string is typically passed to resultSet.getString (columnName) method is the same. column NOTE: To deal with composite keys, you can specify a plurality of column names by column = "{prop1 = col1, prop2 = col2}" syntax to pass this to the nested query. This causes prop1 and prop2 to set the parameter object for the target nested query.
select another complex type mapping statement ID, you can load the desired property mapping. Values listed in the column specified in the properties acquired will be passed to the target select statement as parameters. There is a detailed example of the table below. select NOTE: To deal with composite keys, you can specify a plurality of column names by column = "{prop1 = col1, prop2 = col2}" syntax to pass this to the nested query. This can lead to prop2 with prop1 and parameter object set target nested queries.
fetchType optional. Valid values are lazy and eager. If used, it will replace the global configuration parameters lazyLoadingEnabled.

Example:

<The resultMap ID = "blogResult" type = "Blog">
  <Association Property = "author" column = "the author_id" the javaType = "the Author" SELECT = "selectAuthor" />
</ The resultMap>

<SELECT ID = "selectBlog" The resultMap = "blogResult">
  the SELECT * the FROM BLOG the WHERE ID = # { } the above mentioned id
</ the SELECT>

<the SELECT the above mentioned id = "selectAuthor" resultType = "Author">
  the SELECT * the FROM AUTHOR the WHERE ID = # {the above mentioned id}
</ the SELECT>

we have two queries: a blog to load, the other to load author, and the results of the mapping blog describes "selectAuthor" statement should be used to load its author property.

All other properties will be loaded automatically assuming their column and property names match.

This approach is simple, but to large-scale data collection and list will not perform well. This problem is known of the "N + 1 query problem." Generally speaking, N + 1 selects problem is caused like this:

    You execute a single SQL statement to retrieve a list (the "+1").
    Each record of the return, You execute a select statement to load details for each (that is, "N").

This problem will lead to hundreds of thousands of SQL statements to be executed. This is usually not desirable.

MyBatis can lazy load such queries a benefit, so you can spread the consumption of these statements to run concurrently. However, if you load a list and then immediately iterate to access the nested data, you will invoke all of the lazy loads, and thus performance could be very bad.

So there is another way.
Results associated with the nested
attribute description
resultMap ID This is the result of the mapping, the mapping can be associated to the results of a nested object suitable FIG. This is an alternative method to call another query. This allows you joint multiple tables into a single result set resultMap. Such a result will contain duplicated, repeating groups of data needs to be decomposed and mapped to a nested object in FIG. To facilitate this, MyBatis lets you "link" result maps together, to deal with the nested results. An example would be easy to follow, and one follows this table is an example.
When columnPrefix When connecting multiple tables, you will have to use a column alias to avoid ResultSet duplicate column names. Designated columnPrefix allows you to map the results column name to an external focus. See the examples that follow.
Under notNullColumn default, the only sub-objects in at least one column mapped to their property is not empty when created. By specifying a non-empty column on this property will change the default behavior when you do Mybatis the only non-empty when you create a child object in these columns. You can specify multiple column names, separated by commas. Default: not set (unset).
autoMapping If used, when the result is mapped to the current property, Mybatis will enable or disable automatic mapping. This property overrides the global auto-mapping behavior. Note that it has no effect outside the result set, so select or resultMap this property is meaningless. The default value: not provided (unset).

You've already seen an example of nested associations a very complex. The following is a very simple example to illustrate how it works. Instead of executing a separate statement, our joint blog and Author tables together, like:

<the SELECT the above mentioned id = "selectBlog" resultMap = "blogResult">
  the SELECT
    B.id AS blog_id,
    b.title AS BLOG_TITLE,
    B.author_id blog_author_id AS,
    A.id the author_id AS,
    a.username AS author_username,
    A.password AS author_password,
    A.email AS author_email,
    A.bio AS author_bio
  from the Join Blog the Author A B Outer left ON B.author_id = A.id
  WHERE B the above mentioned id = {} # .id
</ the SELECT>

Notice the join, as well as the care taken to ensure that all results are unique and clear name to rename. This makes mapping is very simple. Now we can map the results:

<resultMap the above mentioned id = "blogResult" of the type = "Blog">
  <id property="id" column="blog_id" />
  <result property="title" column="blog_title"/>
  <association property="author" column="blog_author_id" javaType="Author" resultMap="authorResult"/>
</resultMap>

<resultMap id="authorResult" type="Author">
  <id property="id" column="author_id"/>
  <result property="username" column="author_username"/>
  <result property="password" column="author_password"/>
  <result property="email" column="author_email"/>
  <result property="bio" column="author_bio "/> In the example above, you can see the relevance of the blog represents" authorResult "to load the results of examples.
</ resultMap>



Very Important: id elements play a very important role in the nested result map. You should always specify one or more attributes can uniquely identify the results. In fact, if you do not specify it, then, MyBatis can still work, but can have serious performance problems. In the case that uniquely identifies the results, as few select Properties. A primary key is an obvious choice (even a composite primary key).

Now, the above example used the external element to map the result of associations. This makes the result Author maps can be reused. However, if you do not need to reuse it, or if you simply your result mappings mapping the result to a single bonded described. You can be nested result mappings. Here are the same exemplary embodiment of this use:

<The resultMap ID = "blogResult" type = "Blog">
  <Property ID = "ID" column = "blog_id" />
  <Property Result = "title" column = "BLOG_TITLE" />
  <Association Property = "author" the javaType = "the author">
    <ID Property = "ID" column = "the author_id" />
    <Result Property = "username" column = "author_username" />
    <Result Property = "password" column = "


  </ Association or>
</ resultMap>

If there is a co-author blog how to do? select statement would look like this:

<= select the above mentioned id "selectBlog" resultMap = "blogResult">
  select
    B.id AS blog_id,
    b.title AS BLOG_TITLE,
    A.id AS author_id,
    a.username AS author_username,
    A.password AS author_password,
    A.email AS author_email,
    A.bio AS author_bio,
    CA.id AS co_author_id,
    CA.username AS co_author_username,
    CA.password AS co_author_password,
    CA.email AS co_author_email,
    CA.bio AS co_author_bio
  from Blog B



















  <Result Property = "title" column = "BLOG_TITLE" />
  <Association Property = "author"
    The resultMap = "authorResult" />
  <Association Property = "Coauthor"
    The resultMap = "authorResult"
    columnPrefix = "CO_" />
</ The resultMap >

you've seen above how to deal with the associated "has a" type. But "there are lots of" What? The following section is to discuss this topic.
Set

<= Collection Property "Posts" ofType = "domain.blog.Post">
  <Property ID = "ID" column = "the post_id" />
  <Property Result = "Subject" column = "post_subject" />
  <= Result Property "body" column = "post_body" />
</ Collection>

Action and the associated collection element are almost identical. In fact, it's so similar, to document the similarities would be redundant. So let's focus on the differences.

Let's continue the above example, a blog only one author. But there are many blog articles. Blog class, which may be represented by something like the following:

Private List <Post> Posts;

To map a set of nested results to a List, we use the collection element. Just like the association element, we can use nested queries from the connection, or nested results.
A collection of nested query

First, let's look at using a nested select to load the Posts for the blog.

<resultMap the above mentioned id = "blogResult" of the type = "Blog">
  <Collection Property = "Posts" the javaType = "ArrayList" column = "the above mentioned id" ofType = "Post" the SELECT = "selectPostsForBlog" />
</ resultMap>

<the SELECT the above mentioned id = "selectBlog" The resultMap = "blogResult">
  the SELECT * the FROM BLOG the WHERE ID = # {ID}
</ SELECT>

<SELECT ID = "selectPostsForBlog" the resultType = "Post">
  the SELECT * the FROM the POST the WHERE blog_id = # {ID}
</ select>

here you should pay attention to many things, but above most of the code and the associated elements are very similar. First of all, You should note that we use the collection element. Then we'll notice the new "ofType" attribute. This property is used to distinguish JavaBean (or field) and the type of the attribute type is included in the collection is important. So you can read the following mapping like this:

<collection property = "posts" javaType = "ArrayList" column = "id" ofType = "Post" select = "selectPostsForBlog" />

read: "Post collection type of an ArrayList of posts."

the javaType attribute is not required because in many cases MyBatis will work out for you. So you can shorten the wording:

<Collection Property = "Posts" column = "the above mentioned id" ofType = "Post" the SELECT = "selectPostsForBlog" />
 

Published 966 original articles · won praise 11 · views 30000 +

Guess you like

Origin blog.csdn.net/xiaoyaGrace/article/details/105270742