我有一个spring-dta-jpa应用程序。在运行一些JUnit测试之前,我想填充嵌入式H2数据库。我知道这可以通过将一个data.sql文件放入我的maven项目的资源文件夹中来完成,如spring doc中所述。
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html
我的问题是:如何在该data.sql文件中初始化父子(“one-to-many”)关系?当我想插入子实体时,我不知道父代的ID。
答案 0 :(得分:0)
如果你使用Long作为ID(而不是UUID),那么你的ID很可能从1开始,并且匹配与data.sql中出现的记录相同的顺序
实体关系的例子:
@Entity
public class Document {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, length=256)
@Size(min=1,max=256)
private String name;
private String code;
private Date date;
@OneToMany(mappedBy = "document", cascade = CascadeType.ALL)
@JsonManagedReference
private List<DocumentItem> documentItems;
@Entity(name="document_item")
public class DocumentItem {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, length=256)
private String name;
private BigDecimal price;
@ManyToOne(optional = false)
@JsonBackReference
private Document document;
在上面的示例中,document_id列将添加到document_item实体中。
您还可以使用JoinColumn注释指定列名,该注释用于关系,例如:
@ManyToOne(optional = false)
@JoinColumn(name = "publisher_id")
private Publisher publisher;
示例初始化脚本:
INSERT INTO document(name, code) VALUES ('Test Document 1', 'TD-1');
INSERT INTO document(name, code) VALUES ('Test Document 2', 'TD-2');
INSERT INTO document(name, code) VALUES ('Test Document 3', 'TD-3');
INSERT INTO document(name, code) VALUES ('Test Document 4', 'TD-4');
INSERT INTO document(name, code) VALUES ('Test Document 5', 'TD-5');
INSERT INTO document_item(document_id, name, price) VALUES (2,'Test Item 2.A', 100.45);
INSERT INTO document_item(document_id, name, price) VALUES (2,'Test Item 2.B', 30.45);
INSERT INTO document_item(document_id, name, price) VALUES (2,'Test Item 2.C', 564);
INSERT INTO document_item(document_id, name, price) VALUES (4,'Test Item 4.A', 1);
INSERT INTO document_item(document_id, name, price) VALUES (4,'Test Item 4.B', 456);
INSERT INTO document_item(document_id, name, price) VALUES (5,'Test Item 5.A', 67);
INSERT INTO document_item(document_id, name, price) VALUES (2,'Test Item 2.D', 98);