Mybatis+Mysql返回主鍵
(1)
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.demo.User">
insert into user(userName,password,desc) values(#{userName},#{password},#{desc})
</insert>
(2)
<insert id="insert" parameterType="com.demo.User">
<selectKey keyProperty="id" resultType="Long" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
insert into user(userName,password,desc) values(#{userName},#{password},#{desc})
</insert>
useGeneratedKeys:
取值範圍true|false。預設值是:false。
含義:設定是否使用JDBC的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設定的屬性中。MySQL和SQLServer執行auto-generated key field,因此當資料庫設定好自增長主鍵後,可通過JDBC的getGeneratedKeys方法獲取。但像Oralce等不支援auto-generated key field的資料庫就不能用這種方法獲取主鍵了。
keyProperty:
含義:被設定的目標屬性, MyBatis 會通過 getGeneratedKeys 或者selectKey 子元素設定它的值。預設: 不設定。我們在insert中指定了keyProperty="id",其中id代表插入的User物件的主鍵屬性。
order:
含義:可以被設定為 BEFORE 或 AFTER。如果設定為 BEFORE,那麼它會首先選擇主鍵,設定 keyProperty 然後執行插入語句。如果設定為 AFTER,那麼先執行插入語句,然後是 selectKey 元素,要想取得正確的key值,應設為AFTER。
public class User {
private Long id; //主鍵
private String userName;
private String password;
private String desc;
//setter and getter
}
public interface UserService {
public int insert(User user);
}
User user = new User();
user.setUserName("test");
user.setPassword("123456");
user.setDesc("測試插入返回主鍵");
userService.insert(user);
Long id = user.getId();