In Layman's MyBatis series (vii)---Mapper mapping file configuration Insert, UPDATE, delete[Goto]

Source: Internet
Author: User

In the article "Simple MyBatis Series (vi)---objectfactory, plugins, Mappers Introduction and Configuration" Simply put a full stop to the MyBatis configuration. So from the beginning of this article, will introduce the mapper mapping file configuration, this is one of the core of MyBatis, must learn. In the mapper file, with mapper as the root node, the following element nodes that can be configured are: SELECT, INSERT, UPDATE, delete, cache, Cache-ref, Resultmap, SQL.

This article will briefly introduce the INSERT, UPDATE, delete configuration and use, in the future will be the source of mybatis in-depth explanation.

Believe, see INSERT, UPDATE, Delete, we know its role, as the name implies, Myabtis as a persistent layer framework, must be to crud AH.

OK, let's take a look at INSERT, UPDATE, delete How to configure, which elements can be configured:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//ibatis.apache.org//dtd mapper 3.0//en" "Http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd" & Gt <!--mapper is the root element node, one namespace corresponds to a DAO--><mapper namespace= "Com.dy.dao.UserDao" > <insert <!--1 .         The ID (must be configured) ID is a unique identifier in the namespace that can be used to represent the statement.            A namespace (namespace) corresponds to a DAO interface, which should also correspond to a method within DAO (equivalent to the implementation of a method), so the ID should match the method name--id= "Insertuser" <!--2. ParameterType (optional configuration, default MyBatis automatic selection Processing) The fully qualified class name or alias of the parameter that will pass in the statement, and if it is not configured, MyBatis will select the appropriate Typehandl by default based on the parameter type Parameterhandler ER processing parametertype primarily specifies the type of parameter, either int, short, long, string, or complex type (such as Object)---Parametertype= "Com.dem O.user "<!--3. Flushcache (optional configuration, default configured to TRUE) sets it to true, and whenever a statement is called, both the local cache and the level two cache are emptied, with the default value: True (corresponding to insert, UPDATE, and DELETE statements)--flus Hcache= "true" <!--4. StatementType (optional configuration, default configuration is PREPARED) one of statement,prepared or callable. This will make MyBatis use Statement,preparedstatement or CallableStatement, respectively, with the default value: PREPARED. --Statementtype= "PREPARED" <!--5. Keyproperty (optional configuration, default unset), which is only useful for insert and update, uniquely marks an attribute, MyBatis either through Getgeneratedkeys return value or through the INSERT statement Selec The TKey child element sets its key value, by default: unset. If you want to get more than one generated column, you can also be a comma-delimited list of property names. --Keyproperty= "" <!--6. KeyColumn (optional configuration) (useful for INSERT and update only) sets the column name in the table by the generated key value, which is 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 be a comma-delimited list of property names. --Keycolumn= "" <!--7. Usegeneratedkeys (optional configuration, default = False) (only useful for insert and update) This causes MyBatis to use the JDBC Getgeneratedkeys method to remove the primary key generated by the database (for example,  : A relational database management system such as MySQL and SQL Server automatically increments the field), the default value: False. --usegeneratedkeys= "false" <!--8. Timeout (optional configuration, default unset, dependent driver) This setting is the number of seconds that the driver waits for the database to return request results before throwing an exception. The default value is unset (dependent driver). --timeout= > <update id= "updateUser" parametertype= "Com.demo.User"      Flushcache= "true" statementtype= "PREPARED" timeout= "> <delete id=" DeleteUser "Parame Tertype= "Com.demo.User" flushcache= "true" statementtype= "PREPARED" timeout= "></mapper>"

Above is a template configuration, which is the necessary configuration, which is based on their actual needs, a glance to know.

Below, or use the first article, "MyBatis series (a)---mybatis introduction" in the demo to sample it:

Database (user table):

My Project structure:

User.java:

View Code

Userdao.java:

View Code

Userdao.xml:

View Code

In this way, a simple mapping relationship is established. Careful observation of the above ParameterType, "Com.dy.entity.User", the package name if it is longer, every time this write, write the egg hurts. Do not forget the previous typealiases (alias), then this place, with the alias, it is not the skill and the long bag name of the egg to say goodbye. All right, let's go with an alias. Of course it is in the MyBatis global profile (my name is mybatis-conf.xml), do not assume that is in the mapper configuration file inside the ha.

Mybatis-conf.xml:

<typeAliases>      <!--      through the package, you can directly specify the name of the packages, MyBatis will automatically scan the JavaBean you specify under the packet,      and an alias is set by default. The default name is: JavaBean's first lowercase unqualified class name as its alias. You      can also customize aliases in JavaBean plus annotations @alias, for example: @Alias (user)       <package name= "com.dy.entity"/>-      < Typealias alias= "user" type= "com.dy.entity.User"/>  </typeAliases>

In this way, an alias is taken, we can change the above com.dy.entity.User directly to the User. How convenient it is!

My database is MySQL, I set the user table's primary key ID automatically grow, the above code is working properly, then the problem (of course, I am not asked to learn the excavator which strong), I would like to replace the Oracle database? Oracle does not support ID self-growth ah? What to do? Please see below:

<!--corresponds to Insertuser method in Userdao,--   <insert id= "Insertuser" parametertype= "Com.dy.entity.User" >           <!--Oracle, etc. does not support ID self-growth, can be generated according to its ID policy, first get the ID                    <selectkey resulttype= "int" order= "before" keyproperty= "id" >              select Seq_user_id.nextval as ID from dual        </selectKey>--                insert INTO              user (ID, name, Password, age, Deleteflag)                values (#{id}, #{name}, #{password}, #{age}, #{deleteflag})   </insert>

Similarly, if we are using MySQL and want to return the inserted ID after the data is inserted, we can also use the Selectkey element:

<!--corresponds to Insertuser method in Userdao,--   <insert id= "Insertuser" parametertype= "Com.dy.entity.User" >           <!--Oracle, etc. does not support ID self-growth, can be generated according to its ID policy, first get the ID                    <selectkey resulttype= "int" order= "before" keyproperty= "id" >              select Seq_user_id.nextval as ID from dual        </selectKey>                -                 <!--MySQL after inserting data, get ID-- >        <selectkey keyproperty= "id" resulttype= "int" order= "after" >               select LAST_INSERT_ID () as ID           </selectKey>                     INSERT into user (ID, name, password, age, Deleteflag)                values (#{id}, #{name}, #{password}, #{age}, #{deleteflag})   </insert>

Here, let's simply mention the <selectKey> element node:

<selectkey        <!--The Selectkey statement result should be set to the target property. If you want to get more than one generated column, you can also be a comma-delimited list of property names.        --keyproperty= "id"        <!--the type of result. MyBatis can usually be extrapolated, but there's no problem in writing. MyBatis allows any simple type to be used as the primary key type, including strings. If you want to work on more than one generated column, you can use an Object or a Map that contains the desired property.        --resulttype= "int"        <!--this can be set to before or after. If set to before, it first selects the primary key, sets Keyproperty, and then executes the INSERT statement. If set to After, then the INSERT statement is executed first, then the Selectkey element-this is similar to the Oracle database, and there may be embedded index calls inside the INSERT statement. --        order= "before"        <!--the same as before, MyBatis supports the mapping types for statement,prepared and callable statements, respectively, representing PreparedStatement and The CallableStatement type. --        statementtype= "PREPARED" >

OK, this article mainly introduces the configuration and usage of INSERT, UPDATE, delete. The next article will introduce the complex select-related configuration and usage, after these are all finished, will be based on the source code analysis of the mybatis of the entire running process, and then deep mybatis usage.

This is the end of this article!

Attached demo:http://pan.baidu.com/s/1gdtkf5l

What you need is available for download.

In layman MyBatis series (vii)---Mapper mapping file configuration Insert, UPDATE, delete[to]

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.