
insert、update、delete元素
获取主键方式
- 若数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),则可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置到目标属性上。(自增在xml不需要传入主键id参数,mysql插入数据主键会自增)
<!-- public int insertEmployee(Employee employee); -->
<!--
让MyBatis自动的将自增id赋值给传入的employee对象的id属性
useGeneratedKeys="true":原生jdbc获取自增主键的方法;
keyProperty="":将刚才自增的id封装给哪个属性
-->
<insert id="insertEmployee" useGeneratedKeys="true"<!--取出数据库内部生成的主键-->
keyProperty="id">
insert into t_employee(empname,email,gender) values (#{empName},#{email},#{gender})
</insert>
@Test
public void test03() throws IOException {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
Employee caizelin = new Employee(null, "caizelin", "1111@qq。com", 0);
mapper.insertEmployee(caizelin);
System.out.println(caizelin);//此时id就就会获取到
} finally {
sqlSession.commit();
sqlSession.close();
}
}
- 而对于不支持自增型主键的数据库(例如 Oracle),则可以使用 selectKey 子元素:selectKey 元素将会首先运行,id 会被设置,然后插入语句会被调用(非自增需要在xml中传入id参数,该id参数是提前计算出来的)
<!-- public int insertEmployee2(Employee employee); -->
<insert id="insertEmployee2">
<!--查询主键
order="BEFORE":
在核心sql语句之前先运行一个查询sql查到id;将查到的id赋值给javaBean的哪个属性;
-->
<selectKey order="BEFORE" resultType="integer" keyProperty="id">;<!-- keyProperty:赋值给javaBean的某个属性-->
select max(id)+1 from t_employee//获取目前数据库中最大的索引然后加一
</selectKey>
INSERT INTO t_employee(id,empname,gender,email)
VALUES(#{id},#{empName},#{gender},#{email})
</insert>
@Test
public void test03() throws IOException {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
Employee caizelin = new Employee(null, "caizelin", "1111@qq。com", 0);
mapper.insertEmployee2(caizelin);
System.out.println(caizelin);//此时id就就会获取到
} finally {
sqlSession.commit();
sqlSession.close();
}
}
本文介绍了在SQL映射文件中如何处理自增和非自增主键的方法。对于支持自动生成主键的数据库,如MySQL和SQL Server,可以通过useGeneratedKeys属性和keyProperty来获取自增主键。而在不支持自增主键的数据库,如Oracle,需使用selectKey元素配合插入语句来设置非自增主键。
881

被折叠的 条评论
为什么被折叠?



