mybatis详解-(8)配置自增主键
来源:互联网 发布:sdspage电泳结果数据 编辑:程序博客网 时间:2024/05/01 20:47
延续上一篇增删改查,在添加的时候使用的是数据库的自增主键,如果换成oracle这种没有自增主键的就无法实现,并且保存完成之后,在程序中是获取不到对象id的。我们打印保存后的对象如下:
1.未配置主键自增
@Test public void testMybatisAdd() {//测试添加 SqlSessionFactory sqlSessionFactory = null; SqlSession sqlSession = null; try { sqlSessionFactory = getSqlSessionFactory(); //openSession可以添加参数,无参数表示不会自动提交,需要手动提交 sqlSession = sqlSessionFactory.openSession();// sqlSession = sqlSessionFactory.openSession(true); EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(); //数据库设置id自增 employee.setLastName("huanan"); employee.setEmail("tang_man@sina.com"); employee.setGender("2"); mapper.addEmployee(employee); System.out.println(employee); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { sqlSession.close(); } }
DEBUG - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@184f6be2]
DEBUG - ==> Preparing: insert into mybatis_employee (last_name,email,gender) values (?,?,?);
DEBUG - ==> Parameters: huanan(String), tang_man@sina.com(String), 2(String)
Employee [id=null, lastName=huanan, email=tang_man@sina.com, gender=2]
这里打印的id=null,mybatis可以通过配置,自动生成主键
2.配置主键自增
在insert
标签中添加两个值
useGeneratedKeys=”true”表示使用自增主键
keyProperty=”id”表示id为自增主键
<!-- 插入方法 --> <insert id="addEmployee" parameterType="org.mybatis.crud.Employee" useGeneratedKeys="true" keyProperty="id"> insert into mybatis_employee (last_name,email,gender) values (#{lastName},#{email},#{gender}); </insert>
再次测试添加方法,可以获取到主键的值id=7
DEBUG - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@1f7030a6]
DEBUG - ==> Preparing: insert into mybatis_employee (last_name,email,gender) values (?,?,?);
DEBUG - ==> Parameters: hussanan(String), tang_@qq.com(String), 2(String)
Employee [id=7, lastName=hussanan, email=tang_@qq.com, gender=2]
3.不存在自增主键数据库如何配置
<!-- 插入方法oracle --> <insert id="addEmployeeo"> <!-- keyProperty=id需要赋值主键的属性,一般都是id order=before表示在插入之前执行该查询 resultType=Integer表示返回值为integer类型 --> <selectKey keyProperty="id" order="BEFORE" resultType="Integer"> select employees_seq.nextval from dual; </selectKey> insert into mybatis_employee (id,last_name,email,gender) values (#{id},#{lastName},#{email},#{gender}); </insert>
- mybatis详解-(8)配置自增主键
- mybatis自增主键配置
- mybatis 自增主键配置
- mybatis自增主键配置
- mybatis 自增主键配置
- mybatis 自增主键配置
- mybatis自增主键配置
- mybatis自增主键配置
- mybatis 自增主键配置
- mybatis 自增主键配置
- mybatis 自增主键配置
- mybatis获取mysql插入的自增主键配置方法
- mybatis获取自增主键
- mybatis自增主键无效
- mybatis+oracle主键自增
- mybatis设置自增主键
- mybatis mysql 主键自增
- mybatis自增主键设置
- Tensorflow 学习与复习 Epoch_4_01 Cifar10_模型训练
- Linux目录管理
- 匿名函数(Lambda表达式)与箭头函数
- http respond header
- VRTK 实现菜单出现在视野前方(HTC设备)
- mybatis详解-(8)配置自增主键
- python怎么实现发现所需目录不存在时新建目录
- mysql中的事务、锁与线程安全
- 7、死锁
- 购买饲料
- Python爬虫-基于深度优先策略的百度百科爬虫
- [机器学习]PCA (主成分分析)详解
- 驱动开发概述
- 【web前端自动化工作环境配置】11. 生产环境的适配