- mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.bitqian.dao.OrdersMapper"><insert id="insertOrders" parameterType="cn.bitqian.entity.Orders" ><!-- 返回新增后的主键值 --><selectKey keyProperty="orderId" resultType="java.lang.Integer" keyColumn="order_id" order="AFTER">SELECT LAST_INSERT_ID()</selectKey>insert into orders values (null, #{orderTime}, #{orderMoney}, #{uid})</insert></mapper>
- entity
package cn.bitqian.entity;import java.util.Date;/*** @author echo lovely* @date 2020年11月11日 上午11:30:40*/public class Orders {private Integer orderId;private Date orderTime;private double orderMoney;private int uid;// setter/getter/toString
}
- dao接口
package cn.bitqian.dao;import cn.bitqian.entity.Orders;/*** 新增orders*/
public interface OrdersMapper {int insertOrders(Orders orders);}
- test
@Testpublic void test2() {SqlSession sqlSession = null;try {// 加载mybatis核心配置文件InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");// 获得session工厂SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 通过session工厂获得sessionsqlSession = sqlSessionFactory.openSession(true);Orders orders = new Orders();orders.setOrderMoney(22);orders.setOrderTime(new Date());orders.setUid(1);OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);int count = ordersMapper.insertOrders(orders);System.out.println("受影响行数: " + count);// 主键值会自动装在对象里面System.out.println("新增数据后的主键值:" + orders.getOrderId());} catch (Exception e) {System.out.println(e);} finally {if (sqlSession != null) {sqlSession.close();}}}
- Oracle/sqlserver
insert结点里面套
<!-- oracle -->
<selectKey resultType="java.lang.Integer" keyProperty="id" order="BEFORE">SELECT 序列名.nextval from dual
</selectKey>
<!-- sql server -->
<selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER">SELECT @@identity
</selectKey>
mysql
<selectKey keyProperty="orderId" resultType="java.lang.Integer" keyColumn="order_id" order="AFTER">SELECT LAST_INSERT_ID()
</selectKey>