select @@Identity 返回自增主鍵的值

風泊月發表於2018-07-06

github地址,點選可下載

首先,對mybatsi進行初始化配置

新建mybatis.xml檔案

<?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>
	<!-- 載入DB連線屬性檔案-->
	<properties resource="jdbc.properties"/>
	<!-- 日誌常量的設定 -->
	<settings>
		<setting name="logImpl" value="STDOUT_LOGGING"/>
	</settings>
	<!-- 配置實體類別名-->
	<typeAliases>
		<!-- <typeAlias type="com.fpy.pojo.Star" alias="Star"/> -->
		<package name="com.bjsxt.pojo"/>
	</typeAliases>
	<!-- 配置執行環境-->
	<environments default="mysqlEnv">
		<environment id="mysqlEnv">
			<!-- 配置事務管理器 -->
			<transactionManager type="JDBC"></transactionManager>
			<!-- 配置資料來源 -->
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}"/>
				<property name="url" value="${jdbc.url}"/>
				<property name="username" value="${jdbc.username}"/>
				<property name="password" value="${jdbc.password}"/>
			</dataSource>
		</environment>
	</environments>
	<!-- 註冊對映檔案-->
	<mappers>
		<mapper resource="com/fpy/mapper/IStarMapper.xml"/>
	</mappers>
</configuration>

新建jdbc.properties檔案

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm
jdbc.username=root
jdbc.password=66666

IStarMapper.xml檔案

<!-- 獲取剛插入的記錄的id -->
	<insert id="getInsertId">
		insert into star(name,age,score) values(#{name},#{age},#{score})
		<!--獲得插入資料的id  拿到自增的主鍵值 -->
		<selectKey resultType="int" keyProperty="id" order="AFTER">
        select @@identity
    </selectKey>
	</insert>

介面檔案

public interface IStarMapper {
	//新增,獲取剛插入的記錄的id
	void getInsertId(Star star);

}

實現類檔案

public class StarMapperImpl implements IStarMapper {
	@Override
	public void getInsertId(Star star) {
		//1.獲取SQLSession物件
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		if (sqlSession != null) {
			//2.運算元據
			int aa = sqlSession.insert("getInsertId", star);
			System.out.println("----->\t" + aa);
			//3.提交事務
			sqlSession.commit();
			//4.關閉SQLSession
			sqlSession.close();
		}
	}

}

測試檔案

	@Test
	public void getInsertId(){
		Star star = new Star("xiaolin1", 20, 99.8);
		System.out.println("======\t"+star);
		starMapper.getInsertId(star);
		System.out.println(star);
	}

輸出結果 :開始輸出時沒有主鍵值的id=null,通過呼叫插入的方法獲得了主鍵值 id =24

======	Star [id=null, name=xiaolin1, age=20, score=99.8]
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 990398217.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3b084709]
==>  Preparing: insert into star(name,age,score) values(?,?,?) 
==> Parameters: xiaolin1(String), 20(Integer), 99.8(Double)
<==    Updates: 1
==>  Preparing: select @@identity 
==> Parameters: 
<==    Columns: @@identity
<==        Row: 24
<==      Total: 1
----->	1
Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3b084709]
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3b084709]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3b084709]
Returned connection 990398217 to pool.
Star [id=24, name=xiaolin1, age=20, score=99.8]






在進行資料新增時,主鍵自增,那麼我們在插入資料的時候可以不指定主鍵id的值,使用預設值即可如

相關文章