In Layman's MyBatis series (vii)---Mapper mapping file configuration insert, UPDATE, delete

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 "><!--mapper is the root element node, and one namespace corresponds to one DAO- -<Mappernamespace= "Com.dy.dao.UserDao">    <Insert<!--1. ID (must be configured) ID is a unique identifier in the namespace that can be used to represent this 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 be identical to the method name-->id= "Insertuser"<!--2. ParameterType (optional configuration, default to MyBatis automatic selection processing) The fully qualified class name or alias of the parameter that will pass in the statement, and if not configured, MyBatis chooses the appropriate T by default by Parameterhandler based on the parameter type Ypehandler processing ParameterType primarily specifies parameter types, which can be either int, short, long, string, or complex type (such as Object) -parametertype= "Com.demo.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) -flushcache= "true"<!--4. StatementType (optional configuration, default configuration is PREPARED) one of statement,prepared or callable. This allows MyBatis to use statement,preparedstatement or CallableStatement, respectively, with the default value: PREPARED.  -statementtype= "PREPARED"<!--5. Keyproperty (optional configuration, default = unset) (only useful for insert and update) uniquely marks an attribute, MyBatis either through Getgeneratedkeys return value or by using the Insert language The Selectkey child element of a sentence 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) (only for Insert and update) set the column name in the table by the generated key value, this setting is only necessary for some databases (like PostgreSQL), which is required when the primary key column is not the first column in the table Reset 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, false by default) (only useful for insert and update) This will enable MyBatis to use the JDBC Getgeneratedkeys method to remove the internal  The generated primary key (for example: an auto-increment field for a relational database management system such as MySQL and SQL Server), 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= "> "<UpdateID= "UpdateUser"ParameterType= "Com.demo.User"Flushcache= "true"StatementType= "PREPARED"Timeout= " the">    <DeleteID= "DeleteUser"ParameterType= "Com.demo.User"Flushcache= "true"StatementType= "PREPARED"Timeout= " the"></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:

 Packagecom.dy.entity; Public classUser {Private intID; PrivateString name; PrivateString password; Private intAge ; Private intDeleteflag;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     Public intGetdeleteflag () {returnDeleteflag; }     Public voidSetdeleteflag (intDeleteflag) {         This. Deleteflag =Deleteflag; }    }
View Code

Userdao.java:

 Package Com.dy.dao; Import Com.dy.entity.User;  Public Interface Userdao {    publicvoid  insertuser (user user);          Public void updateUser (user user);          Public void deleteuser (user user);    }
View Code

Userdao.xml:

<?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 "> <Mappernamespace= "Com.dy.dao.UserDao">      <!--corresponding to the Insertuser method in Userdao, -   <InsertID= "Insertuser"ParameterType= "Com.dy.entity.User">INSERT into user (ID, name, password, age, Deleteflag) VALUES (#{id}, #{name}, #{password}, #{ Age}, #{deleteflag})</Insert>      <!--the UpdateUser method in correspondence Userdao -   <UpdateID= "UpdateUser"ParameterType= "Com.dy.entity.User">Update user set name = #{name}, password = #{password}, age = #{age}, Deleteflag = #{deleteflag}   WHERE id = #{id}; </Update>       <!--the DeleteUser method in correspondence Userdao -    <DeleteID= "DeleteUser"ParameterType= "Com.dy.entity.User">Delete from user where id = #{id}; </Delete></Mapper>
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 specify the package directly      Name, MyBatis will automatically scan you to specify the JavaBean under the package, and by default an alias, 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:

<!--corresponding to the Insertuser method in Userdao, -   <InsertID= "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" &G              T 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 :

<!--corresponding to the Insertuser method in Userdao, -   <InsertID= "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" &G              T Select Seq_user_id.nextval as ID from dual </selectKey> -                 <!--after MySQL inserts the data, gets the ID -        <SelectkeyKeyproperty= "id"Resulttype= "int"Order= "after" >SELECT last_insert_id () as ID</Selectkey>INSERT into user (ID, name, password, age, Deleteflag) VALUES (#{id}, #{name}, #{pa ssWOrd}, #{age}, #{deleteflag})</Insert>

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

<Selectkey<!--The target property that the Selectkey statement result should be set. 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 the 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"<!--as before, MyBatis supports the mapping types for statement,prepared and callable statements, representing PreparedStatement and CallableStatement types, respectively.  -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's MyBatis series (vii)---Mapper mapping file configuration insert, UPDATE, delete

Related Article

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.