1. 程式人生 > >INSERT、UPDATE獲取隨意主鍵生成(selectKey)

INSERT、UPDATE獲取隨意主鍵生成(selectKey)

XML檔案配置:

  1. 與resultType:返回值型別(主鍵型別,可省略)
  2. keyProperty:返回值儲存的屬性或對映指定值
  3. 順序:後/前,
    1. 後:先執行插入語句,再獲取主鍵
    2. 前:先行選擇主鍵列,再執行插入語句
  4. statementType:STATEMENT,PREPARED和CALLABLE語句的對映型別

XML配置:

<mapper namespace="com.parkingms.dao.ILoginDao">
	<insert id="insertLogin" parameterType="com.parkingms.bean.LoginBean">
		<!--插入語句 -->
		INSERT INTO t_login (login_account,login_pwd,login_character) VALUES (#{account},#{pwd},#{character})
		<selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER">
			<!-- 查詢主鍵語句 -->
			select login_id from t_login where
			login_account = #{account}
		</selectKey>
	</insert>
</mapper>

DAO語句:

public interface ILoginDao {
	public boolean insertLogin(LoginBean bean);
}

註解形式配置:

  1. 豆中返回值對應的屬性值需要有獲取/設定方法
  2. 前必須為假,否則會報錯(暫不清楚)
package com.parkingms.dao;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.SelectKey;
import com.parkingms.bean.LoginBean;

public interface ILoginDao {
	@Insert(value = {
			"INSERT INTO t_login "
			+ "(login_account,login_pwd,login_character)"
			+ " VALUES"
			+ "(#{account},#{pwd},#{character})" })
	@SelectKey(before = false, keyProperty = "id", resultType = int.class, statement = { "select login_id from t_login where login_account = #{account}" })
	public boolean insertLogin(LoginBean bean);

}

測試語句:

package com.parkingms.test;
import java.io.IOException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.parkingms.bean.LoginBean;
import com.parkingms.dao.ILoginDao;
public class LoginTest {
	@Test
	public void insertTest() throws IOException {
		LoginBean bean = new LoginBean();
		bean.setAccount("登陸名7");
		bean.setCharacter(1);
		bean.setPwd("登陸密碼");
		SqlSessionFactory fa = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("config/config.xml"),"development");
		SqlSession session = fa.openSession(true);
		ILoginDao dao = session.getMapper(ILoginDao.class);
		boolean s = dao.insertLogin(bean);
		System.out.println(bean.getId());	
	}
}