gpt4 book ai didi

java - 将实体预填充到数据库中以进行测试

转载 作者:行者123 更新时间:2023-11-30 11:12:07 25 4
gpt4 key购买 nike

我正在开发 Java EE 7 应用程序。出于测试目的,用一些内容填充数据库会非常有益。 This tutorial解释了如何使用 SQL 文件在运行时或之前创建数据库内容。我假设,在这个 SQL 文件中,我可以做这样的事情:

INSERT INTO ENTITYNAME(ENTITYATTRIBUTE1, ENTITYATTRIBUTE2, ... ENTITYATTRIBUTEN) value
("entityAttribute1", "entityAttribute2, ... "entityAttributeN")

如果我的方法是正确的,我将如何提供@ElementCollection、@OneToMany 或只是实体属性的值?

最佳答案

如果您想使用 sql 脚本用测试数据预填充数据库,则必须检查 JPA 从您的 @Entity 类生成的模式。

例如,如果您有 2 个 @Entity:

@Entity
public class Foo {
@Id int id;
@ElementCollection Set<String> strings;
@OneToMany(mappedBy"foo") Set<Bar> bars;
}

@Entity
public class Bar {
@Id int id;
@ManyToOne
Foo foo;
}

您将不得不自己检查,但生成的模式可能看起来像这样。

create table Foo {
id int primary key
}

create table Foo_strings {
Foo_id int references Foo (id),
strings varchar,
}

create table Bar {
id int primary key,
Foo_id references Foo(id)
}

所以如果你想在 sql 中创建一些测试数据,你可以创建一个 setup_test_data.sql 如下:

insert into Foo values (1);

insert into Foo_strings values (1, "string 1");
insert into Foo_strings values (1, "string 2");

insert into Bar values (1, 1);
insert into Bar values (2, 1);

这与在字符串 @ElementCollection 和 2 Bar 中包含 2 个 StringFoo 相同> 栏中的 @OneToMany 关系。

关于java - 将实体预填充到数据库中以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27050989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com