INSERT、UPDATE获取随意主键生成(selectKey)

XML文件配置:

  1. 与resultType:返回值类型(主键类型,可省略)
  2. keyProperty:返回值存储的属性或映射指定值
  3. 顺序:后/前,
    1. 后:先执行插入语句,再获取主键
    2. 前:先行选择主键列,再执行插入语句
  4. statementType:STATEMENT,PREPARED和CALLABLE语句的映射类型

XML配置:


	
		
		INSERT INTO t_login (login_account,login_pwd,login_character) VALUES (#{account},#{pwd},#{character})
		
			
			select login_id from t_login where
			login_account = #{account}
		
	

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());	
	}
}

参考:https://blog.csdn.net/isea533/article/details/21153791

你可能感兴趣的:(mybatis)