SQL映射文件获取自增主键和非自增主键的值

本文介绍了在SQL映射文件中如何处理自增和非自增主键的方法。对于支持自动生成主键的数据库,如MySQL和SQL Server,可以通过useGeneratedKeys属性和keyProperty来获取自增主键。而在不支持自增主键的数据库,如Oracle,需使用selectKey元素配合插入语句来设置非自增主键。

在这里插入图片描述

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();
        }
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值