mybatis: 返回主键ID(自增和非自增)

mapper映射文件



<mapper namespace="com.mybatis.mapper.TableNameMapper">
	
	<insert id="insertData" useGeneratedKeys="true" keyProperty="id">
		insert into tableName values(null,#{name})
	insert>
	
	 <insert id="insertDataAgain">
	 	
	 	 
	 	<selectKey resultType="integer" keyProperty="id" order="BEFORE">
	 		SELECT LAST_INSERT_ID()
	 	selectKey>
	 	
		insert into tableName values(null,#{name})
	insert>
mapper>

mapper接口

public interface TableNameMapper {
	//插入数据
	public Integer insertData(TableName tableName);
	//插入数据
	public Integer insertDataAgain(TableName tableName);
}

测试代码:

InputStream inputStream = null;
SqlSessionFactory sqlSessionFactory = null;
SqlSession session = null;
try {
	inputStream = Resources.getResourceAsStream("mybatis-config.xml");
	sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	session = sqlSessionFactory.openSession();
	TableNameMapper mapper = session.getMapper(TableNameMapper.class);
	TableName tableName = new TableName();
	tableName.setName("中文");
	//插入数据方式1
	//mapper.insertData(tableName);
	//插入数据方式2
	mapper.insertDataAgain(tableName);
	session.commit();
	System.out.println(tableName.getId());
	
} catch (IOException e) {
	e.printStackTrace();
}finally {
	try {
		session.close();
		inputStream.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

注: ORACLE返回主键最好是在插入SQL执行之前执行,也就是order属性值设置为before


<selectKey resultType="integer" keyProperty="id" order="AFTER">
	 		SELECT EVE_SQU.nextval FROM dual
selectKey>
<insert id="insertData" useGeneratedKeys="true" keyProperty="id">
		insert into tableName values(#{id},#{name})
insert>

你可能感兴趣的:(mybaits)