一、前情回顾
在修改程序时,我希望在数据中插入一条数据后,在 service 服务层能够知道该数据插入后的主键,一般就是 id 啦。
二、解决方案
在XML中加入 useGeneratedKeys="true" 和 keyProperty="id" 两个属性,然后插入语句执行后,主键( id )就会自动封装到我传进来的 com.lph.ssm.pojo.Stores 里面了,stores.getId() 就能得到想要的主键了。如下
<insert id="addMesStore" parameterType="com.lph.ssm.pojo.Stores" useGeneratedKeys="true" keyProperty="id">
INSERT INTO MES_STORE(S_NAME,C_CODE,L_ID)
VALUES(#{storeName,jdbcType=NVARCHAR},#{checkCode,jdbcType=INTEGER},#{lid,jdbcType=INTEGER})
</insert>
// 添加店铺
Integer result = storeDao.addMesStore(stores);
System.err.println("result==" + result + ", stores.getId()==" + stores.getId());
控制台输出的结果为:result==1, stores.getId()==13
三、知识补充
MySQL:
MySQL有两种方法,第一种和上面的 SQLServer 一样。这里直接演示第二种:
<insert id="addMesStore" parameterType="com.lph.ssm.pojo.Stores">
<selectKey resultType="java.lang.Short" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
INSERT INTO MES_STORE(S_NAME,C_CODE,L_ID)
VALUES(#{storeName,jdbcType=NVARCHAR},#{checkCode,jdbcType=INTEGER},#{lid,jdbcType=INTEGER})
</insert>
取数的方法和上边的一样,getId() 即可。
Oracle:
由于本人暂时没有用Oracle做项目,在网上借鉴了https://blog.csdn.net/Megamind_HL/article/details/81280418的博客,先把知识记录下来,万一下次要用呢。
文章原话:相对于MySql,Sql Server来说,Oracle插入主键返回自增稍显复杂一点,需要一个Sequence和一个Trigger,接下来看代码。Sequence:序列号,创建一个自增的序列号。
Trigger:当做insert操作的时候,触发插入一个从Sequence中获取序列插入主键中。
- Sequence:
create sequence Seq_Test
minvalue 1
maxvalue 100000000000000
start with 1
increment by 1
nocache;缓存序列号,防止系统宕机或者其他情况导致不连续,也可以设置nocache
- Trigger:
create or replace trigger tri_test
before insert on TableName --表名
for each row
declare
nextid number;
begin
IF :new.Id IS NULL or :new.Id=0 THEN --Id是列名,主键
select Seq_Test.nextval --Seq_Test上面创建的序列号
into nextid
from sys.dual;
:new.Id:=nextid;
end if;
end tri_test;
- XML配置
<insert id="add" parameterType="cn.crm.PO">
<selectKey resultType="java.lang.Integer" order="BEFORE(After)" keyProperty="Id">
SELECT Seq_Test.NEXTVAL FROM DUAL
</selectKey>
insert into system_user (name, parent_id,
phone_num, password, description
)
values (#{name,jdbcType=VARCHAR},
#{parent_id,jdbcType=SMALLINT},
#{phone_num,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}
)
</insert>