1.一個 INSERT SQL 語句可以在<insert>元素在映射器 XML 配置文件中配置
例子:
<insert id="insertStudentWithId" parameterType="Student">INSERT INTO Student(id,name,sex,birthday,height,weight,score,address,email,hobby) values(#{id},#{name},#{sex},#{birthday},#{height},#{weight},#{score},#{address},#{email},#{hobby})</insert>
如果使用名空間(namspace)和語句id來調用的話,那么使用的是SqlSession對象的insert()方法,其返回值是執行INSER語句后所影響的行數。
注:
在執行insert語句之后,SqlSession對象必須執行commit進行顯式提交,否則數據庫中的數據不會刷新
2.自動生成主鍵
在上述的 INSERT 語句中,我們為可以自動生成(auto-generated)主鍵的列 id插入值。 我們可以使用
useGeneratedKeys 和 keyProperty 屬性讓數據庫生成 auto_increment 列的值,並將生成的值設置到其中一個
輸入對象屬性內:
useGeneratedKeys 和 keyProperty 屬性讓數據庫生成 auto_increment 列的值,並將生成的值設置到其中一個
輸入對象屬性內:
例子:
xml code
<insertid="insertStudentWithoutId"parameterType="Student"useGeneratedKeys="true"keyProperty="id" >INSERT INTO Student (name,sex,birthday,height,weight,score,address,email,hobby) values(#{name},#{sex},#{birthday},#{height},#{weight},#{score},#{address},#{email},#{hobby})</insert>
java code
@Testpublicvoid testInsertWithoutId(){SqlSession sqlSession =MyBatisSqlSessionFactory.openSession();try{StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);Student student =newStudent();student.setName("小2");student.setAddress("江蘇南通");student.setBirthday(newDate());student.setEmail("xiao2@live.com");student.setHeight(177);student.setHobby("打籃球");student.setScore(99);student.setSex("男");student.setWeight(120);studentMapper.insertStudentWithoutId(student);sqlSession.commit();System.out.println(student);}finally{sqlSession.close();}}
注:
有些數據庫如
Oracle 並不支持 AUTO_INCREMENT 列,
其使用序列(
SEQUENCE)來生成主鍵值
方法一:
假設我們有一個名為 STUD_ID_SEQ 的序列來生成 SUTD_ID 主鍵值。使用如下代碼來生成主鍵:
Xml Code
<insertid="insertStudent"parameterType="Student"><selectKeykeyProperty="id"resultType="int"order="BEFORE">SELECT ELEARNING.STUD_ID_SEQ.NEXTVAL FROM DUAL</selectKey>INSERT INTO STUDENTS(id,name,email, address)VALUES(#{id},#{name},#{email},#{address})</insert>
這里我們使用了<selectKey>子元素來生成主鍵值,並將值保存到 Student 對象的 id 屬性上。 屬性
order=“before”表示 MyBatis 將取得序列的下一個值作為主鍵值,並且在執行 INSERT SQL 語句之前將值設置到
id 屬性上
order=“before”表示 MyBatis 將取得序列的下一個值作為主鍵值,並且在執行 INSERT SQL 語句之前將值設置到
id 屬性上
方法二:
我們也可以在獲取序列的下一個值時,使用觸發器(trigger)來設置主鍵值,並且在執行 INSERT SQL 語句之
前將值設置到主鍵列上。 如果你采取這樣的方式,則對應的 INSERT 映射語句如下所示:
前將值設置到主鍵列上。 如果你采取這樣的方式,則對應的 INSERT 映射語句如下所示:
Xml Code
<insert id="insertStudent" parameterType="Student">INSERT INTO STUDENTS(name,email, address) VALUES(#{name},#{email},#{address})<selectKey keyProperty="studId" resultType="int" order="AFTER">SELECT ELEARNING.STUD_ID_SEQ.CURRVAL FROM DUAL</selectKey></insert>
3.Sql Server顯式插入主鍵
Sql Server中可以設置主鍵自增,但是一旦設置為主鍵自增,我們不可以默認顯式的插入主鍵值
開啟顯式插入主鍵值得sql語句:
SET IDENTITY_INSERT
tableName
ON (OFF為關閉的方法)
注:有時候我們並不需要手動去關閉顯式插入主鍵值,因為在每一個新的數據庫連接中SQL Server會自動調整為默認不開啟
Xml Code
<update id="setIdentityInsert" parameterType="java.lang.String">SET IDENTITY_INSERT Student ${_parameter}</update>
注:
MyBatis中傳入String類型參數的時候,SQL語句中的參數名必須為_parameter
