使用执行INSERT语句中的子插入语句的MyBatis
所以,我有我想要插入到具有以下结构的数据库中的对象使用执行INSERT语句中的子插入语句的MyBatis
int id
String name
Array tags
而且我要插入的第一两列到下表
CREATE TABLE foo (
id number(20) PRIMARY KEY,
name varchar2(50) NOT NULL
);
和阵列到此表
CREATE TABLE fooTags (
id number(20) PRIMARY KEY,
fooId number(20), //foreign key to foo. I don't know what the sql is for that.
tagName varchar2(50)
);
ħ ow会执行一个子插入,它将采用由初始插入工作创建的ID?我假设需要一个SELECT,但我不确定如何命令将所需信息插入到每个对象的适当区域。
我写了2个程序;
如果你可以学习你的seq名称为id;
create or replace procedure FOO_INSERT(foo_name in varchar2, FooTags_tagName in varchar2)
is
foo_seq_val number;
footag_seq_val number;
begin
select foo_seq.nextval into foo_seq_val from dual;
insert into foo(id,name) values (foo_seq_val, foo_name);
select footag_seq.nextval into footag_seq_val from dual;
insert into footags (id,fooid,tagName) values(footag_seq_val,foo_seq_val,FooTags_tagName);
commit;
end;
如果你不能学习你的seq名称为ids;
create or replace procedure FOO_INSERT_T(foo_name in varchar2, FooTags_tagName in varchar2)
is
foo_seq_val number;
begin
insert into foo_T(name) values (foo_name);
select id into foo_seq_val from FOO_T where name =foo_name;
insert into footags_T (fooid,tagName) values(foo_seq_val,FooTags_tagName);
commit;
end;
如果您通过ids;
insert into foo (id, name) values (123,'foo_name');
insert into footags (id,fooid,tagname) select 444,id, 'tag_name' from foo ;
commit;
对于第二个过程我假设你foo_T.name值是唯一的或者您的每一行的其他值让你的ID是唯一的。您可以将您的选择结束与and ... and ..
您可以看到一个COMMIT
每种方法。因为如果出现错误,事务回滚所有插入内容为foo_table
和fooTags_table
。这是准确性。
我的解决办法:两个插入查询,第一部分为父对象(FOO表),第二个他的标签(fooTags表):
<insert id="fooInsert" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
INSERT INTO foo (name) VALUES (#{name})
</insert>
<insert id="fooTagsInsert">
INSERT INTO fooTags ("fooId", "tagName") VALUES
<foreach item="tag" collection="tags" separator=",">
(#{id}, #{tag})
</foreach>
</insert>
属性 “useGeneratedKeys”, “keyProperty” 和“如果JDBC驱动程序支持getGeneratedKeys函数,则使用“keyColumn”从数据库重新加载新生成的密钥。或者,我们必须使用选择查询重新加载标识。更多信息:http://www.mybatis.org/mybatis-3/sqlmap-xml.html#insert_update_and_delete
标签插入使用“foreach”遍历标签名称(在这种情况下,我使用了一个字符串数组,但它们可能是对象)。 “内部”插入引用来自“foo”对象和“标记”的“id”,即迭代字符串。在对象的情况下,我们可以用“标签”访问内部字段,即“tag.name”。
使用Java代码:
Foo foo = new Foo();
foo.setName("James");
foo.setTags(new String[] {"one", "two", "three"});
fooMapper.fooInsert(foo);
fooMapper.fooTagsInsert(foo);
表定义(PostgreSQL的测试):
CREATE TABLE public.foo (
id numeric NOT NULL DEFAULT nextval('seq_foo_id'::regclass),
"name" varchar NULL,
CONSTRAINT foo_pk PRIMARY KEY (id)
)
CREATE TABLE public.footags (
id varchar NOT NULL DEFAULT nextval('seq_foo_id'::regclass),
"fooId" numeric NULL,
"tagName" varchar NULL,
CONSTRAINT footags_pk PRIMARY KEY (id),
CONSTRAINT footags_foo_fk FOREIGN KEY ("fooId") REFERENCES public.foo(id)
)
你想一个程序? –
@mehmetsahin如果这会在mybatis中起作用或很容易转换?我会诚实地说,我不知道这个特定行动的最佳做法是什么。 – canadiancreed
Foo.id和FooTags.id不是一个序列,我认为你通过它们? –