mybatis 添加一条新数据并返回此数据的ID(主键)
2015-12-18 10:21
656 查看
通常数据库中表的主键是‘自动递增(mysql)’或’序列(oracle)‘,但插入数据后又要取得些条数据的ID(将ID做为主键)
利用Mybatis 的 selectKey来获得:
或
<insert id="addDept" parameterType="com.demo.model.Department" useGeneratedKeys="true" keyProperty="id">
insert into department(<include refid="departmentAllField"/>)
values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId});
</insert><span style="font-family: Arial, Helvetica, sans-serif;"></span>
注意:insert 标签中的 keyProperty 和 selectKey标签块中的 LAET_INSERT_ID() ,另外 order属性 对于 oracl为 BEFORE; mysql为AFTER
实体类:
测试:
输出成功!
利用Mybatis 的 selectKey来获得:
<!-- 添加部门 返回部门ID --> <insert id="addDept" parameterType="com.demo.model.Department" keyProperty="id"> <selectKey keyProperty='id' resultType='int' order='AFTER' > select LAST_INSERT_ID(); </selectKey> insert into department(<include refid="departmentAllField"/>) values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId}); </insert>
或
<insert id="addDept" parameterType="com.demo.model.Department" useGeneratedKeys="true" keyProperty="id">
insert into department(<include refid="departmentAllField"/>)
values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId});
</insert><span style="font-family: Arial, Helvetica, sans-serif;"></span>
注意:insert 标签中的 keyProperty 和 selectKey标签块中的 LAET_INSERT_ID() ,另外 order属性 对于 oracl为 BEFORE; mysql为AFTER
实体类:
public class Department { private int id; private int departmentId; private String departmentName; private String departmentManagerName; private int companyId; private List<Employee> employees; //...GET SET ... }
测试:
@Test public void testDao(){ deptDao = session.getMapper(DepartmentDao.class); Department department = new Department(); department.setDepartmentName("ares"); department.setDepartmentManagerName("tom"); department.setDepartmentId(32); department.setCompanyId(6201); deptDao.addDept(department); System.out.println("新部门ID:"+department.getId()); }
输出成功!
相关文章推荐
- 深入浅析mybatis oracle BLOB类型字段保存与读取
- oracle+mybatis 使用动态Sql当插入字段不确定的情况下实现批量insert
- 浅析Mybatis 在CS程序中的应用
- Java Mybatis框架入门基础教程
- Java简单实现SpringMVC+MyBatis分页插件
- 浅析mybatis和spring整合的实现过程
- mybatis的动态sql详解(精)
- MyBatis入门学习教程(一)-MyBatis快速入门
- Spring与Mybatis的整合方法有哪些
- 解决springmvc+mybatis+mysql中文乱码问题
- Spring+Mybatis+Mysql搭建分布式数据库访问框架的方法
- SpringMVC+MyBatis项目总结(一)
- SpringMVC+MyBatis项目总结(二)
- MyBatis返回结果不稳定
- MyBatis通过反射建立一个对象的过程。
- springMVC+spring+Mybatis
- SpringMVC+mybatis+Spring框架整合+简单实现的demo
- 笔记:学习JavaWeb开发第三课
- Spring+mybatis+shiro+freemarker+ehcache+ldap+mongo
- 继续钟爱JdbcTemplate