Mybatis series (7) --- insert, update, delete of mapper mapping file configuration

Mybatis series (7) --- insert, update, delete time of mapper mapping file configuration
time 2014-10-27 09:24:00 Blog Garden - Java
original http://www.cnblogs.com/dongying/p/4048828 .html
theme MyBatis database
This article will briefly introduce the configuration and use of insert, update, delete, and will give an in-depth explanation of the source code of mybatis in the future.

I believe that when we see insert, update, delete, we will know its function. As the name suggests, myabtis, as a persistence layer framework, must be CRUD-friendly.

Well, let's take a look at how to configure insert, update, delete, and what 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, one namespace corresponds to one dao -->
<mapper namespace="com.dy.dao.UserDao">

    <

        id is a unique identifier in the namespace that can be used to represent this statement.
        A namespace (namespace) corresponds to a dao interface, and
        this id should also correspond to a method in dao (equivalent to the implementation of the method), so the id should be consistent with the method name -->
     
      id="insertUser"
     
      <!-- 2 . parameterType (optional configuration, the default is mybatis automatic selection processing)
        the fully qualified class name or alias of the parameter to be passed into the statement, if not configured, mybatis will select the appropriate typeHandler by default according to the parameter type for processing
        parameterType mainly specifies the parameters Type, which can be int, short, long, string, etc., or complex types (such as objects) -->
     
      parameterType="com.demo.User"
     
      <!-- 3. flushCache (optional configuration, the default configuration is true)
        Set it to true, whenever a statement is called, both the local cache and the second-level cache will be emptied, default value: true (corresponding to insert, update and delete statements) -->
     
      flushCache="true"
     
      <! -- 4. statementType (optional configuration, the default configuration is PREPARED)
        One of STATEMENT, PREPARED or CALLABLE. This will make MyBatis use Statement, PreparedStatement or CallableStatement respectively, default value: PREPARED. -->
     
      statementType="PREPARED"
     
      <!-- 5. keyProperty (optional configuration, default is unset)
        (only useful for insert and update) uniquely mark a property, MyBatis will pass the return value of getGeneratedKeys or pass the selectKey of the insert statement The child element sets its key value, default: unset. It can also be a comma-separated list of property names if multiple generated columns are desired. -->
     
      keyProperty=""
     
      <!-- 6. keyColumn (optional configuration)
        (only useful for insert and update) Set the column name in the table through the generated key value, this setting is only available in some databases (like PostgreSQL) It is required and needs to be set when the primary key column is not the first column in the table. It can also be a comma-separated list of property names if multiple generated columns are desired. -->
     
      keyColumn=""
     
      <!-- 7. useGeneratedKeys (optional, default is false)
        (Only for insert and update) This will cause MyBatis to use JDBC's getGeneratedKeys method to retrieve primary keys generated internally by the database (eg: auto-increment fields in relational database management systems like MySQL and SQL Server), default: false. -->
     
      useGeneratedKeys="false"
     
      <!-- 8. timeout (optional configuration, default is unset, depends on the driver)
        This setting is the number of seconds that the driver waits for the database to return the request result before throwing an exception. The default value is unset (depending on the driver). -->
      timeout="20">

    <update
      id="updateUser"
      parameterType="com.demo.User"
      flushCache="true"
      statementType="PREPARED"
      timeout="20">

    <delete
      id="deleteUser"
      parameterType= "com.demo.User"
      flushCache="true"



The above is a template configuration, which are necessary configurations and which are based on your actual needs, you can know at a glance.

Next, let's use the demo in the first article "Mybatis Series (1)---Introduction to Mybatis" as an example:

Database (user table):


My project structure:


User.java:


package com.dy.entity;

public class User {

  private int id;
  private String name;
  private String password;
  private int age;
  private int deleteFlag;
 
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public int getDeleteFlag() {
    return deleteFlag;
  }
  public void setDeleteFlag(int deleteFlag) {
    this.deleteFlag = deleteFlag;
  }
 
}
View Code
UserDao.java:


package com.dy.dao;

import com.dy.entity.User;

public interface UserDao {

  public void 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">

<mapper namespace="com.dy.dao.UserDao">
  
   <!-- 对应userDao中的insertUser方法,  -->
   <insert id="insertUser" parameterType="com.dy.entity.User">
       insert into user(id, name, password, age, deleteFlag)
         values(#{id}, #{name}, #{password}, #{age},#{deleteFlag})    <!-- corresponds to the updateUser method in userDao-->
   </insert>
  

   <update id="updateUser" parameterType="com.dy.entity.User">
       update user set name = #{name}, password = #{password}, ​​age = #{age}, deleteFlag = #{deleteFlag}
         where id = #{id};
   </update>
 
   <!-- corresponds to the deleteUser method in userDao-->
   <delete id="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. Carefully observe the above parameterType, "com.dy.entity.User", if the package name is longer, it will be painful to write like this every time. Don't forget the typeAliases (aliases) we talked about earlier, so if you use aliases in this place, isn't it a skill to say goodbye to the long package name that hurts. Okay, let's match the alias, where is it? Of course, it is in the global configuration file of mybatis (my name here is mybatis-conf.xml), don't think it is configured in the configuration file of mapper.

mybatis-conf.xml:



  Through package, you can directly specify the name of the package, mybatis will automatically scan the javabeans under the specified package,
  and set an alias by default. The default name is: javabean The unqualified class name of the lowercase first letter is used as its alias.
  You can also add annotation @Alias ​​to javabean to customize the 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, and we can directly change the above com.dy.entity.User to user. How convenient!

My database here is mysql. I set the primary key id of the user table to grow automatically, and the above code runs normally, then the problem comes (of course, I don’t want to ask which is the best excavator), if I replace it with an oracle database How to do? But oracle does not support id self-growth? How to do? Please see the following:

<!-- Corresponding to the insertUser method in userDao, -->
   <insert id="insertUser" parameterType="com.dy.entity.User">
       <!-- oracle etc. do not support id self-growth, The strategy can be generated according to its id, first get the 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 want to return the inserted id after data insertion when using mysql, we can also use the selectKey element:

<!-- corresponds to the insertUser method in userDao, -->
   <insert id="insertUser" parameterType="com.dy.entity.User">
       <!-- oracle, etc. do not support id self-growth, you can generate the strategy according to its id, first get the id
      
    <selectKey resultType=" int" order="BEFORE" keyProperty="id">
      select seq_user_id.nextval as id from dual
    </selectKey>
   
    -->
   
    <! -- After mysql inserts data, get the 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 briefly mention the <selectKey> element node:

<selectKey
  <!-- selectKey statement result should be set target property. It can also be a comma-separated list of property names if multiple generated columns are desired. -->
  keyProperty="id"
  <!-- The type of the result. MyBatis can usually be calculated, but there is no problem in writing it for more certainty. MyBatis allows any simple type to be used as a primary key type, including strings. If you want to act on multiple generated columns, you can use an Object or a Map containing the desired properties. -->
  resultType="int"
  <!-- This can be set to BEFORE or AFTER. If set to BEFORE, then it will first select the primary key, set the keyProperty and then execute the insert statement. If set to AFTER, the insert statement is executed first, followed by the selectKey element - this is similar to databases like Oracle, which may have embedded index calls inside the insert statement. -->
  order="BEFORE"
  <!-- Same as before, MyBatis supports the mapping types of STATEMENT, PREPARED and CALLABLE statements, representing PreparedStatement and CallableStatement respectively. -->
  statementType="PREPARED">
Well, this article mainly introduces the configuration and usage of insert, update, delete. The next article will introduce complex select-related configuration and usage. After all these are finished, I will first analyze the entire running process of mybatis according to the source code, and then go deep into the usage of mybatis.

This article ends here!

Attach the demo download address: http://pan.baidu.com/s/1gdtKf5L

can be downloaded if needed.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326998429&siteId=291194637