咱們知道MySql中主鍵能夠設成auto_increment,也就是自增主鍵,每當新增一條記錄,主鍵值自動加1。java
在MyBatis中,執行insert,返回值爲受影響的語句行數,此操做跟JDBC一致。mysql
可是若是應用中須要將插入的值的主鍵返回時,這時有兩種方式:sql
第一種方式:在mapper的insert節點中添加useGeneratedKey和keyProperty屬性數據庫
第二種方式:在mapper的insert節點下添加selectKey子節點的方式apache
下面是具體的使用方式舉例:session
1、MySql中mybatis數據庫的users表結構 mybatis
+----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(50) | YES | | NULL | | | password | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+----------------+
2、MyBatis配置文件 mybatis-config.xml
app
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 在properties節點下定義的屬性能夠在全局中進行引用,具體引用的方式是 ${屬性名} --> <properties> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="zzlibdmt"/> </properties> <!-- 爲domain設置別名,注意:只能爲javaBean設置別名,而不是mapper文件中的id --> <typeAliases> <package name="cn.kolbe.mybatis.domain"/> </typeAliases> <!-- environments下能夠有多個environment節點,表示不一樣的開發環境,只要有一個與default匹配便可 --> <!-- 具體在開發中,能夠在開發時使用development配置,上線時使用production配置等等 --> <environments default="development"> <environment id="development"> <!-- JDBC表示直接使用底層JDBC的事務管理 --> <transactionManager type="JDBC"></transactionManager> <!-- 配置POOLED將使用MyBatis的自帶的數據庫鏈接池 --> <!-- 具體屬性名字能夠查看該類的setter方法 --> <!-- org.apache.ibatis.datasource.pooled.PooledDataSource --> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/kolbe/mybatis/domain/UserMapper.xml"/> </mappers> </configuration>
3、MyBatis的mapper映射文件 UserMapper.xmldom
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/mybatis-3-mapper.dtd"> <mapper namespace="cn.kolbe.mybatis.domain.UserMapper"> <insert id="getGeneratedKey1" parameterType="cn.kolbe.mybatis.domain.User"> insert into users(name, password) values(#{name}, #{password}) </insert> <!-- useGeneratedKeys默認值爲false,keyProperty的值對應的是User類中的主鍵名 --> <insert id="getGeneratedKey2" parameterType="cn.kolbe.mybatis.domain.User" useGeneratedKeys="true" keyProperty="id"> insert into users(name, password) values(#{name}, #{password}) </insert> <insert id="getGeneratedKey3" parameterType="cn.kolbe.mybatis.domain.User"> <!-- 使用這種方式要注意,resultType是要設置的,不然將拋異常,該值對應的User類中的主鍵類型 --> <!-- keyProperty對應的是User類中的主鍵名,假設取名爲user_id,則這邊也要改爲user_id --> <selectKey keyProperty="id" resultType="int"> select LAST_INSERT_ID() </selectKey> insert into users(name, password) values(#{name}, #{password}) </insert> </mapper>
4、普通的Java實體類Useride
package cn.kolbe.mybatis.domain; public class User { private Integer id; private String name; private String password; public User(String name, String password) { this.name = name; this.password = password; } public Integer getId() { return id; } public void setId(Integer 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; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + "]"; } }
5、測試代碼
package cn.kolbe.mybatis; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import cn.kolbe.mybatis.domain.User; public class MyBatisTest { /** * 普通的插入操做 * * @throws FileNotFoundException */ @Test public void testGetGeneratedKey1() throws FileNotFoundException { SqlSession session = factory.openSession(); String statement = "cn.kolbe.mybatis.domain.UserMapper.getGeneratedKey1"; User user = new User("User_01","123456"); int result = session.update(statement, user); // result爲受影響的行數 session.commit(); System.out.println(user); // 輸出 User [id=null, name=User_02, password=123456] System.out.println("result:" + result); // 輸入 result: 1 } /** * 在insert中添加了 useGeneratedKeys="true" keyProperty="id" 屬性的插入操做 * * @throws FileNotFoundException */ @Test public void testGetGeneratedKey2() throws FileNotFoundException { SqlSession session = factory.openSession(); String statement = "cn.kolbe.mybatis.domain.UserMapper.getGeneratedKey2"; User user = new User("User_02","123456"); // 此時MyBatis不只返回了受影響的行數,還將自增的id賦值給了傳進去的user // 這時能夠看到user打印出來的id是有值的!!! int result = session.update(statement, user); // 受影響的行數 session.commit(); System.out.println(user); // 輸出 User [id=2, name=User_02, password=123456] System.out.println("result:" + result); // 輸出 result: 1 } /** * 在insert中添加子節點<selectKey>子節點的插入操做 * <selectKey order="AFTER" keyProperty="id"> * select select last_insert_id() * </selectKey> * * @throws FileNotFoundException */ @Test public void testGetGeneratedKey3() throws FileNotFoundException { SqlSession session = factory.openSession(); String statement = "cn.kolbe.mybatis.domain.UserMapper.getGeneratedKey3"; User user = new User("User_03", "123456"); // 此時MyBatis不只返回了受影響的行數,還將自增的id賦值給了傳進去的user // 這時能夠看到user打印出來的id是有值的!!! int result = session.update(statement, user); // 受影響的行數 session.commit(); System.out.println(user); // 輸出 User [id=3, name=User_03, password=123456] System.out.println("result:" + result); // 輸出 result: 1 } /** * 初始化SessionFactory * @throws Exception */ @Before public void init() throws Exception { InputStream in = new FileInputStream("src/main/java/mybatis-config.xml"); factory = new SqlSessionFactoryBuilder().build(in); } private SqlSessionFactory factory; }
注:
1)使用selectKey的方式獲取主鍵,至關於調用了MySql的LAST_INSERT_ID()函數,意思是查詢最後一次插入的ID,至關於執行了兩條語句
2)兩種方式的主鍵獲取方式都是經過MyBatis爲咱們自動將id值賦值給傳入的javaBean,而不是經過update語句返回,也就是update返回的同jdbc一致(影響的行數),獲取id的方式是執行完update後調用user.getId()方法,具體可參看上面的例子。