In-depth introduction to Mybatis series (7) --- insert, update, delete, and mybatis --- mapper in mapper ing file configuration
In the previous article, the introduction and configuration of Mybatis series (6) --- objectFactory, plugins, and mappers briefly end the configuration of mybatis. Starting from this article, we will introduce the configuration of the ER er ing file, which is one of the core of mybatis and must be learned well. In the mapper file, mapper is used as the root node. The following element nodes can be configured: select, insert, update, delete, cache, cache-ref, resultMap, and SQL.
This article will briefly introduce the configuration and use of insert, update, and delete. The source code of mybatis will be explained in detail later.
I believe that when we see insert, update, and delete, we will know its role. As the name suggests, myabtis, as a persistent layer framework, must be against CRUD.
Well, let's take a look at how to configure insert, update, and 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, and a namespace corresponds to a dao --> <mapper namespace = "com. dy. dao. UserDao"> <insert <! -- 1. id (required) id is the unique identifier in the namespace and can be used to represent this statement. A namespace corresponds to a dao interface, and this id should also correspond to a method (equivalent to the implementation of the method) in dao ), therefore, the id must be the same as the method name --> id = "insertUser" <! -- 2. parameterType (optional, which is automatically selected for processing by mybatis by default) the fully qualified class name or alias of the parameters to be passed in the statement. If this parameter is not configured, mybatis selects an appropriate typeHandler Based on the parameter type through ParameterHandler to process parameterType. The parameter type can be int, short, long, string, etc, it can also be a complex type (such as an object) --> parameterType = "com. demo. user "<! -- 3. flushCache (optional, set to true by default) is set to true. If a statement is called at any time, the local cache and the second-level cache are cleared. Default Value: true (corresponding to insert, update, and delete statements) --> flushCache = "true" <! -- 4. statementType (optional, PREPARED by default) One of STATEMENT, PREPARED, or CALLABLE. This causes MyBatis to use Statement, PreparedStatement, or CallableStatement respectively. The default value is PREPARED. --> StatementType = "PREPARED" <! -- 5. keyProperty (optional, unset by default) (used only for insert and update) uniquely identifies an attribute, myBatis sets its key value through the getGeneratedKeys return value or the selectKey sub-element of the insert statement. The default value is unset. If you want to obtain multiple generated columns, you can also use a list of attribute names separated by commas. --> KeyProperty = "" <! -- 6. keyColumn (optional) (used only for insert and update) sets the column name in the table through the generated key value. This setting is only required in some databases (such as PostgreSQL, when the primary key column is not the first column in the table, you need to set it. If you want to obtain multiple generated columns, you can also use a list of attribute names separated by commas. --> KeyColumn = "" <! -- 7. useGeneratedKeys (optional, false by default) (only useful for insert and update) This will allow MyBatis to use the getGeneratedKeys method of JDBC to retrieve the primary keys generated inside the database (for example: automatically incrementing fields of the relational database management system such as MySQL and SQL Server). Default Value: false. --> UseGeneratedKeys = "false" <! -- 8. timeout (optional, default: unset, dependent driver) this setting is the number of seconds the driver waits for the database to return the request result before an exception is thrown. The default value is 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 are necessary configurations and which are based on your actual needs.
Next, let's use the demo in the first article "go deep into Mybatis series (1) --- Mybatis getting started" 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 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"> <! -- Corresponds to the insertUser method in userDao, --> <insert id = "insertUser" parameterType = "com. dy. entity. user "> insert into user (id, name, password, age, deleteFlag) values (# {id}, # {name}, # {password}, # {age }, # {deleteFlag}) </insert> <! -- Corresponding to the updateUser method in userDao --> <update id = "updateUser" parameterType = "com. dy. entity. user "> update user set name =#{ name}, password =#{ password}, age =#{ age }, deleteFlag =#{ deleteFlag} where id =#{ id}; </update> <! -- Corresponding 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 ing relationship is established. Take a closer look at parameterType, "com. dy. entity. User", and set the package name to a longer value. It hurts to write it every time. Don't forget the typeAliases (alias) mentioned earlier. In this case, it's not a skill or a long package name. Okay, let's get an alias. Where should we get it? Of course it is in the global configuration file of mybatis (my name is mybatis-conf.xml here), do not think it is configured in the mapper configuration file.
Mybatis-conf.xml:
<TypeAliases> <! -- With package, you can directly specify the package name. mybatis automatically scans the javabean under the specified package and sets an alias by default. The default name is: the lowercase non-qualified class name of a javabean is used as its alias. You can also add the annotation @ Alias to the 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, a single name is ready. We can change the above com. dy. entity. User to user. This is convenient!
Mysql is used in the database here. I set the primary key id of the user table to automatically increase and the above Code runs normally. The problem arises (of course, I am not asking which excavator is the best ), what if I change to an oracle database? Does oracle Support auto-increment of IDs? What should I do? See the following:
<! -- Corresponds to the insertUser method in userDao, --> <insert id = "insertUser" parameterType = "com. dy. entity. User"> <! -- If oracle does not support auto-increment of IDS, policies can be generated based on their IDs, obtain 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 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"> <! -- If oracle does not support auto-increment of IDS, policies can be generated based on their IDs, obtain the id <selectKey resultType = "int" order = "BEFORE" keyProperty = "id"> select seq_user_id.nextval as id from dual </selectKey> --> <! -- Obtain the id AFTER mysql inserts data --> <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, we will briefly mention the <selectKey> element node:
<SelectKey <! -- The target attribute that the selectKey statement result should be set. If you want to obtain multiple generated columns, you can also use a list of attribute names separated by commas. --> KeyProperty = "id" <! -- Result type. MyBatis can be computed normally, but it won't be a problem to be more specific. MyBatis allows any simple type to be used as the primary key type, including strings. If you want to act on multiple generated columns, you can use an Object or a Map containing the expected attributes. --> ResultType = "int" <! -- This can be set to BEFORE or AFTER. If it is set to BEFORE, it first selects the primary key, sets the keyProperty, and then executes the insert statement. If it is set to "AFTER", the insert statement is executed first, followed by the selectKey element. This is similar to Oracle databases, and an embedded index call may be performed within the insert statement. --> Order = "BEFORE" <! -- Similar to the previous one, MyBatis supports the stating types of STATEMENT, PREPARED, and CALLABLE statements, representing the PreparedStatement and CallableStatement types respectively. --> StatementType = "PREPARED">
Well, this article mainly introduces the configuration and usage of insert, update, and delete. In the next article, we will introduce the complex select-related configuration and usage. After all these are done, we will first analyze the entire mybatis running process based on the source code, and then go into the usage of mybatis.
This article ends now!
Attached demo: http://pan.baidu.com/s/1gdtKf5L
Yes.
How to configure mybatis SQL mering mapper file merge statements
Mybatis is not hibernate, no marge
In fact, isn't marge a combination of insert and update?
When I first learned about mybatis, when I wrote a DEMO, insert, update, and delete all succeeded. If I run the select statement, an error is returned.
Send the select Configuration xml to see if