代碼直接放在Github倉庫【https://github.com/Damaer/Mybatis-Learning/tree/master/mybatis-05-CURD 】
需要聲明的是:此Mybatis
學習筆記障斋,是從原始的Mybatis
開始的,而不是整合了其他框架(比如Spring
)之后,個人認為半等,這樣能對它的功能蜈缤,它能幫我們做什么拾氓,有更好的理解,后面再慢慢疊加其他的功能底哥。
我們知道很多時候我們有一個需求咙鞍,我們需要把插入數(shù)據(jù)后的id返回來,以便我們下一次操作趾徽。
其實一開始的思路是我插入之后续滋,再執(zhí)行一次select,根據(jù)一個唯一的字段來執(zhí)行select
操作孵奶,但是Student
這個類如果插入后再根據(jù)名字或者年齡查出來疲酌,這根本就是不可行的!A嗽朗恳!重名與同年齡的人一定不少。
我們的測試方法如下,我們可以看到插入前是沒有值的载绿,插入后就有了值:
/**
* 測試插入后獲取id
*/
@Test
public void testinsertStudentCacheId(){
Student student=new Student("helloworld",17,85);
System.out.println("插入前:student="+student);
dao.insertStudentCacheId(student);
System.out.println("插入后:student="+student);
}
useGeneratedKeys 設置主鍵自增
<insert id="insertStudentCacheId" useGeneratedKeys="true" keyProperty="id" parameterType="Student">
insert into student(name,age,score) values(#{name},#{age},#{score})
</insert>
需要注意的點:
- 1.
useGeneratedKeys="true"
表示設置屬性自增 - 2.
keyProperty="id"
設置主鍵的字段 - 3.
parameterType="Student"
設置傳入的類型 - 4.注意:雖然有返回類型粥诫,但是我們不需要手動設置返回的類型,這個是由框架幫我們實現(xiàn)的崭庸,所以對應的接口方法也是沒有返回值的,會修改我們插入的對象怀浆,設置id值。
- 5.實體類中id屬性字段一定需要set以及get方法
使用selectKey 查詢主鍵
<insert id="insertStudentCacheId" parameterType="Student">
insert into student(name,age,score) values(#{name},#{age},#{score})
<!-- 指定結(jié)果類型resultType怕享,keyProperty是屬性执赡,自動返回到屬性id中,order是次序函筋,after是指獲取id是在于插入后 -->
<selectKey resultType="int" keyProperty="id" order="AFTER">
select @@identity
</selectKey>
</insert>
或者寫成:
<insert id="insertStudentCacheId" parameterType="Student">
insert into student(name,age,score) values(#{name},#{age},#{score})
<!-- 指定結(jié)果類型resultType沙合,keyProperty是屬性,自動返回到屬性id中跌帐,order是次序灌诅,after是指獲取id是在于插入后 -->
<selectKey resultType="int" keyProperty="id" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
</insert>
注意要點:
- 1.最外層的
<insert></insert>
沒有返回屬性(resultType)
,但是里面的<selectKey></selectKey>
是有返回值類型的含末。 - 2.
order="AFTER"
表示先執(zhí)行插入猜拾,之后才執(zhí)行selectkey
語句的。 - 3.
select @@identity
和select LAST_INSERT_ID()
都表示選出剛剛插入的最后一條數(shù)據(jù)的id佣盒。 - 4.實體類中id屬性字段一定需要set以及get方法
- 5.此時挎袜,接口中仍不需要有返回值,框架會自動將值注入到我們
insert
的那個對象中,我們可以直接使用就可以了盯仪。
其實紊搪,我們的接口中可以有返回值,但是這個返回值不是id,而是表示插入后影響的行數(shù)全景,此時sql中仍和上面一樣耀石,不需要寫返回值。
<insert id="insertStudentCacheIdNoReturn" parameterType="Student">
insert into student(name,age,score) values(#{name},#{age},#{score})
<!-- 指定結(jié)果類型resultType爸黄,keyProperty是屬性滞伟,自動返回到屬性id中,order是次序炕贵,after是指獲取id是在于插入后 -->
<selectKey resultType="int" keyProperty="id" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
</insert>
接口中:
// 增加新學生并返回id返回result
public int insertStudentCacheId(Student student);
接口的實現(xiàn)類:
public int insertStudentCacheId(Student student) {
int result;
try {
sqlSession = MyBatisUtils.getSqlSession();
result =sqlSession.insert("insertStudentCacheId", student);
sqlSession.commit();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return result;
}
Test中:
public void testinsertStudentCacheId(){
Student student=new Student("helloworld",17,101);
System.out.println("插入前:student="+student);
int result = dao.insertStudentCacheId(student);
System.out.println(result);
System.out.println("插入后:student="+student);
}
結(jié)果證明:result的值為1梆奈,表示插入了一行,查看數(shù)據(jù)庫称开,確實插入了數(shù)據(jù)亩钟。
PS:如果無法創(chuàng)建連接,需要把Mysql
的jar包升級:
<!-- mysql驅(qū)動包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
如果報以下的錯誤鳖轰,那么需要將&改成轉(zhuǎn)義后的符號&
:
org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 107; 對實體 "serverTimezone" 的引用必須以 ';' 分隔符結(jié)尾清酥。
在xml里面配置需要轉(zhuǎn)義,不在xml文件里面配置則不需要
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&serverTimezone=UTC"/>
【作者簡介】:
秦懷蕴侣,公眾號【秦懷雜貨店】作者总处,技術之路不在一時,山高水長睛蛛,縱使緩慢,馳而不息胧谈。這個世界希望一切都很快忆肾,更快,但是我希望自己能走好每一步菱肖,寫好每一篇文章客冈,期待和你們一起交流。