MyBatis Mapper XML file-mapping and parameters

Source: Internet
Author: User

MyBatis Mapper XML file-mapping and parameters


The true strength of MyBatis lies in its mapping statement and its magic. Because of its exceptional power, the mapper's XML file appears relatively simple. If you compare it to a JDBC code that has the same functionality, you'll immediately find that you've skipped nearly 95% of the code. MyBatis is built for SQL and is better than normal methods.

The SQL mapping file has a few top-level elements (in the order in which they should be defined): cache– the cache configuration for a given namespace. cache-ref– a reference to another namespace cache configuration. Resultmap– is the most complex and powerful element used to describe how to load objects from a database result set. sql– A reusable statement block that can be referenced by other statements. insert– mapping INSERT Statement update– Mapping UPDATE statement delete– Mapping DELETE Statement select– mapping query statement Select (query)

Query statement is one of the most commonly used elements in mybatis, the light energy to save data to the database is not very valuable, if you can also be removed to be useful, most applications are also query than to modify frequently. For each insert, update, or delete operation, multiple query operations are usually appropriate. This is one of the basic principles of mybatis, as well as the reason to put focus and effort into query and result mapping. The select element of a simple query is very simple. Like what:

<select id= "Selectperson" parametertype= "int" resulttype= "HashMap" >

SELECT * from person WHERE ID = #{id}

</select>

This statement, called Selectperson, accepts an int (or Integer) type argument and returns an object of type HashMap, where the key is the column name, and the value is the corresponding value in the result row.

Note the parameter symbols:

#{id}

This tells MyBatis to create a preprocessing statement parameter, which, through JDBC, would be a "?" in SQL. To identify and be passed into a new preprocessing statement, like this:

Similar JDBC code, not MyBatis ...

String Selectperson = "SELECT * from person WHERE id=?";

PreparedStatement PS = conn.preparestatement (Selectperson);

Ps.setint (1, id);

Of course, this requires a lot of separate JDBC code to extract the results and map them to object instances, which is where MyBatis saves you time. We need to drill down to the parameters and result mappings, the detail section below, and we understand that the SELECT element has many attributes that allow you to configure the action details of each statement:

Property

Description

Id

A unique identifier in a namespace that can be used to reference this statement.

ParameterType

The fully qualified name or alias of the parameter class that will pass in the statement. This property is optional because mybatis can infer the arguments for the specific incoming statement by Typehandler, and the default value is unset.

Resulttype

The fully qualified name or alias of the class of the desired type returned from this statement. Note that if it is a collection case, it should be the type that the collection can contain, not the collection itself. Use Resulttype or Resultmap, but not at the same time.

Resultmap

A named reference to an external resultmap. The mapping of result sets is the most powerful feature of MyBatis, and with a good understanding of it, many complex mapping situations can be solved. Use Resultmap or Resulttype, but not at the same time.

Flushcache

Set to True, any time a statement is invoked, both the local cache and the level two cache are emptied, with the default value: False.

UseCache

Setting this to true will cause the result of this statement to be cached by level two, the default value: True for the SELECT element.

Timeout

This setting is the number of seconds that the driver waits for the database to return the requested result before an exception is thrown. The default value is unset (dependent drive).

Fetchsize

This is an attempt to influence the driver to return the number of rows per batch and this setting value is equal. The default value is unset (dependent drive).

StatementType

One of the statement,prepared or callable. This will allow MyBatis to use statement,preparedstatement or CallableStatement respectively, the default value: PREPARED.

ResultsetType

One of the forward_only,scroll_sensitive or scroll_insensitive, the default value is unset (dependent driver).

DatabaseId

If Databaseidprovider,mybatis is configured, all statements that do not take databaseId or match the current databaseId are loaded, and if there are any statements with or without them, the ones that are not taken are ignored.

Resultordered

This setting applies only to nested results SELECT statements: If true, it is assumed that a nested result set or grouping is included, so that when a primary result row is returned, there is no reference to the previous result set. This allows the nesting result set to be obtained without causing insufficient memory. Default value: False.

ResultSets

This setting applies only to the case of a multiple result set, which lists the result sets returned after the statement is executed and each result set to a name that is comma-delimited.

Insert, UPDATE, and DELETE statements

The implementation of the data change statement insert,update and delete is very close:

<insert

Id= "Insertauthor"

Parametertype= "Domain.blog.Author"

Flushcache= "true"

Statementtype= "PREPARED"

Keyproperty= ""

Keycolumn= ""

Usegeneratedkeys= ""

Timeout= ">"

<update

Id= "Updateauthor"

Parametertype= "Domain.blog.Author"

Flushcache= "true"

Statementtype= "PREPARED"

Timeout= ">"

<delete

Id= "Deleteauthor"

Parametertype= "Domain.blog.Author"

Flushcache= "true"

Statementtype= "PREPARED"

Timeout= ">"

Property

Description

Id

A unique identifier in a namespace that can be used to represent this statement.

ParameterType

The fully qualified class name or alias of the parameter to which the statement will be passed. This property is optional because mybatis can infer the arguments for the specific incoming statement by Typehandler, and the default value is unset.

Flushcache

Set to True, any time a statement is invoked, both the local cache and the level two cache are emptied, with the default value: True (corresponding to insert, UPDATE, and DELETE statements).

Timeout

This setting is the number of seconds that the driver waits for the database to return the requested result before an exception is thrown. The default value is unset (dependent drive).

StatementType

One of the statement,prepared or callable. This will allow MyBatis to use statement,preparedstatement or CallableStatement respectively, the default value: PREPARED.

Usegeneratedkeys

(Only useful for inserts and updates) This will allow MyBatis to use the JDBC Getgeneratedkeys method to remove the primary keys generated by the database internally (for example: Automatic increment fields for relational database management systems like MySQL and SQL Server) ), default value: False.

Keyproperty

(Only useful for inserts and updates) uniquely marks a property, MyBatis the key value by Getgeneratedkeys's return value or through the Selectkey child element of the INSERT statement, by default: unset. If you want to get more than one generated column, you can also have a comma-delimited list of property names.

KeyColumn

(Only useful for inserts and updates) The column names in the table are set by the generated key values, which are required only for certain databases (like PostgreSQL), which need to be set when the primary key column is not the first column in the table. If you want to get more than one generated column, you can also have a comma-delimited list of property names.

DatabaseId

If Databaseidprovider,mybatis is configured, all statements that do not take databaseId or match the current databaseId are loaded, and if there are any statements with or without them, the ones that are not taken are ignored.

First, if your database supports fields that automatically generate primary keys (such as MySQL and SQL Server), then you can set usegeneratedkeys= "true" and then set the Keyproperty to the target attribute to OK. For example, if the Author table above has already used auto-generated column types for IDs, the statement can be modified to:

<insert id= "Insertauthor" usegeneratedkeys= "true"

keyproperty= "id" >

Insert into Author (Username,password,email,bio)

VALUES (#{username},#{password},#{email},#{bio})

</insert>

If your database also supports MultiRow inserts, you can also pass in a authors array or collection and return the Auto-generated primary key:

<insert id= "Insertauthor" usegeneratedkeys= "true"

keyproperty= "id" >

INSERT into Author (username, password, email, bio) values

<foreach item= "Item" collection= "List" separator= "," >

(#{item.username}, #{item.password}, #{item.email}, #{item.bio})

</foreach>

</insert>

MyBatis has another way to generate primary keys for databases that do not support the auto-generated type or for a JDBC driver that may not support automatic generation of primary keys. Here's a simple (even silly) example that generates a random ID (you'd better not do it, but here's a demonstration of the flexibility and breadth of mybatis handling issues):

<insert id= "Insertauthor" >

<selectkey keyproperty= "id" resulttype= "int" order= "before" >

Select CAST (RANDOM () *1000000 as INTEGER) a from SYSIBM. SYSDUMMY1

</selectKey>

INSERT INTO Author

(ID, username, password, email,bio, favourite_section)

Values

(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouritesection,jdbctype=varchar})

</insert>

In the above example, the Selectkey element will run first, the Author ID will be set, and the INSERT statement will be invoked. This gives you a similar behavior to dealing with the Auto-generated primary key in the database, avoiding the complexity of the Java code. The Selectkey element is described as follows:

tr> the target property that the

Properties

description

Keyproperty

Selectkey statement results should be set. If you want to get more than one generated column, you can also have a comma-delimited list of property names. The

KeyColumn

Matches the column names in the result set for the property. If you want to get more than one generated column, you can also have a comma-delimited list of property names. The type of result for the

Resulttype

. MyBatis can usually be extrapolated, but there's no problem in writing for more certainty. MyBatis allows any simple type to be used as a primary key type, including strings. If you want to work with more than one generated column, you can use an Object or a Map that contains the desired attributes.

Order

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.