


An in-depth explanation of the Mybatis series (7)---insert, update, delete of mapper mapping file configuration
The previous article "In-depth introduction to Mybatis series (6)---Introduction and configuration of objectFactory, plugins, mappers" simply concluded the configuration of mybatis. So starting from this article, we will introduce the configuration of the mapper mapping file. This is one of the cores of mybatis, and you must learn it well. In the mapper file, with mapper as the root node, the element nodes that can be configured below it are: select, insert, update, delete, cache, cache-ref, resultMap, sql.
This article will briefly introduce the configuration and use of insert, update, delete, and will provide an in-depth explanation of the source code of mybatis in the future.
I believe that when we see insert, update, and delete, we will know its function. As the name suggests, myabtis, as a persistence layer framework, must handle CRUD.
Okay, let’s first 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 为根元素节点, 一个namespace对应一个dao --><mapper namespace="com.dy.dao.UserDao"> <insert <!-- 1. id (必须配置) id是命名空间中的唯一标识符,可被用来代表这条语句。 一个命名空间(namespace) 对应一个dao接口, 这个id也应该对应dao里面的某个方法(相当于方法的实现),因此id 应该与方法名一致 --> id="insertUser" <!-- 2. parameterType (可选配置, 默认为mybatis自动选择处理) 将要传入语句的参数的完全限定类名或别名, 如果不配置,mybatis会通过ParameterHandler 根据参数类型默认选择合适的typeHandler进行处理 parameterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象) --> parameterType="com.demo.User" <!-- 3. flushCache (可选配置,默认配置为true) 将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:true(对应插入、更新和删除语句) --> flushCache="true" <!-- 4. statementType (可选配置,默认配置为PREPARED) STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。 --> statementType="PREPARED" <!-- 5. keyProperty (可选配置, 默认为unset) (仅对 insert 和 update 有用)唯一标记一个属性,MyBatis 会通过 getGeneratedKeys 的返回值或者通过 insert 语句的 selectKey 子元素设置它的键值,默认:unset。如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。 --> keyProperty="" <!-- 6. keyColumn (可选配置) (仅对 insert 和 update 有用)通过生成的键值设置表中的列名,这个设置仅在某些数据库(像 PostgreSQL)是必须的,当主键列不是表中的第一列的时候需要设置。如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。 --> keyColumn="" <!-- 7. useGeneratedKeys (可选配置, 默认为false) (仅对 insert 和 update 有用)这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系数据库管理系统的自动递增字段),默认值:false。 --> useGeneratedKeys="false" <!-- 8. timeout (可选配置, 默认为unset, 依赖驱动) 这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)。 --> timeout="20"> <update id="updateUser" parameterType="com.demo.User" flushCache="true" statementType="PREPARED" timeout="20"> <delete id="deleteUser" parameterType="com.demo.User" flushCache="true" statementType="PREPARED" timeout="20"></mapper>
The above is a template configuration , which ones are necessary configurations and which ones are based on your actual needs, you can know at a glance.
Next, let’s use the demo in the first article "In-depth introduction to Mybatis series (1)---Getting started with 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; } }
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); }
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}) </insert> <!-- 对应userDao中的updateUser方法 --> <update id="updateUser" parameterType="com.dy.entity.User"> update user set name = #{name}, password = #{password}, age = #{age}, deleteFlag = #{deleteFlag} where id = #{id}; </update> <!-- 对应userDao中的deleteUser 方法 --> <delete id="deleteUser" parameterType="com.dy.entity.User"> delete from user where id = #{id}; </delete></mapper>
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 written like this every time, and it will be painful to write. Don't forget the typeAliases (aliases) mentioned before. So, using aliases in this place, wouldn't it mean that the skill says goodbye to the painfully long package name? Okay, let’s match the alias, where should we match it? Of course, it is in the global configuration file of mybatis (my name here is mybatis-conf.xml). Don't think that it is configured in the mapper configuration file.
mybatis-conf.xml:
<typeAliases> <!-- 通过package, 可以直接指定package的名字, mybatis会自动扫描你指定包下面的javabean, 并且默认设置一个别名,默认的名字为: javabean 的首字母小写的非限定类名来作为它的别名。 也可在javabean 加上注解@Alias 来自定义别名, 例如: @Alias(user) <package name="com.dy.entity"/> --> <typeAlias alias="user" type="com.dy.entity.User"/> </typeAliases>
In this way, an alias is created. We can add all the above com.dy.entity.User Directly changed to user. How convenient this is!
My database here uses mysql. I set the primary key id of the user table to automatically grow. The above code runs normally, so here comes the problem (of course, I am not asking which excavator company Strong), what if I switch to Oracle database? Oracle does not support self-increment of IDs? what to do? Please see below:
<!-- 对应userDao中的insertUser方法, --> <insert id="insertUser" parameterType="com.dy.entity.User"> <!-- oracle等不支持id自增长的,可根据其id生成策略,先获取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>
同理,如果我们在使用mysql的时候,想在数据插入后返回插入的id, 我们也可以使用 selectKey 这个元素:
<!-- 对应userDao中的insertUser方法, --> <insert id="insertUser" parameterType="com.dy.entity.User"> <!-- oracle等不支持id自增长的,可根据其id生成策略,先获取id <selectKey resultType="int" order="BEFORE" keyProperty="id"> select seq_user_id.nextval as id from dual </selectKey> --> <!-- mysql插入数据后,获取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>
这儿,我们就简单提一下
<selectKey <!-- selectKey 语句结果应该被设置的目标属性。如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。 --> keyProperty="id" <!-- 结果的类型。MyBatis 通常可以推算出来,但是为了更加确定写上也不会有什么问题。MyBatis 允许任何简单类型用作主键的类型,包括字符串。如果希望作用于多个生成的列,则可以使用一个包含期望属性的 Object 或一个 Map。 --> resultType="int" <!-- 这可以被设置为 BEFORE 或 AFTER。如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 元素 - 这和像 Oracle 的数据库相似,在插入语句内部可能有嵌入索引调用。 --> order="BEFORE" <!-- 与前面相同,MyBatis 支持 STATEMENT,PREPARED 和 CALLABLE 语句的映射类型,分别代表 PreparedStatement 和 CallableStatement 类型。 --> statementType="PREPARED">
以上就是深入浅出Mybatis系列(七)---mapper映射文件配置之insert、update、delete的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

iBatis vs. MyBatis: Which should you choose? Introduction: With the rapid development of the Java language, many persistence frameworks have emerged. iBatis and MyBatis are two popular persistence frameworks, both of which provide a simple and efficient data access solution. This article will introduce the features and advantages of iBatis and MyBatis, and give some specific code examples to help you choose the appropriate framework. Introduction to iBatis: iBatis is an open source persistence framework

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Several ways to implement batch deletion statements in MyBatis require specific code examples. In recent years, due to the increasing amount of data, batch operations have become an important part of database operations. In actual development, we often need to delete records in the database in batches. This article will focus on several ways to implement batch delete statements in MyBatis and provide corresponding code examples. Use the foreach tag to implement batch deletion. MyBatis provides the foreach tag, which can easily traverse a set.

Detailed explanation of how to use MyBatis batch delete statements requires specific code examples. Introduction: MyBatis is an excellent persistence layer framework that provides rich SQL operation functions. In actual project development, we often encounter situations where data needs to be deleted in batches. This article will introduce in detail how to use MyBatis batch delete statements, and attach specific code examples. Usage scenario: When deleting a large amount of data in the database, it is inefficient to execute the delete statements one by one. At this point, you can use the batch deletion function of MyBatis

Detailed explanation of MyBatis caching mechanism: One article to understand the principle of cache storage Introduction When using MyBatis for database access, caching is a very important mechanism, which can effectively reduce access to the database and improve system performance. This article will introduce the caching mechanism of MyBatis in detail, including cache classification, storage principles and specific code examples. 1. Cache classification MyBatis cache is mainly divided into two types: first-level cache and second-level cache. The first-level cache is a SqlSession-level cache. When

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values
