因此,我尝试将一个对象插入到具有以下结构的数据库中
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)
);如何执行子插入,它将采用初始插入所创建的id?我假设需要SELECT,但我不确定如何排序才能将所需信息插入到每个对象的适当区域。
发布于 2017-08-08 00:55:42
我写了2个程序;
如果你能记住你的If的序号;
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;如果您不能记住If的序号名称;
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 ..对select语句的末尾进行排序
您可以看到每个方法都有一个COMMIT。因为如果出现错误,事务将回滚您对foo_table和fooTags_table插入的所有内容。这就是准确性。
发布于 2017-08-09 00:35:52
我的解决方案:两个insert查询,第一个是父对象(foo表),第二个是his标签(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>如果JDBC驱动程序支持getGeneratedKeys函数,则属性"useGeneratedKeys“、"keyProperty”和"keyColumn“用于从数据库重新加载新生成的键。或者,我们必须使用select查询重新加载id。更多信息:http://www.mybatis.org/mybatis-3/sqlmap-xml.html#insert_update_and_delete
标签插入使用"foreach“遍历标签名称(在本例中我使用了字符串数组,但它们可以是对象)。“内部”插入引用来自"foo“对象的"id”和"tag",即迭代字符串。在对象的情况下,我们可以使用"tag.",即"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)
)https://stackoverflow.com/questions/45551099
复制相似问题