【发布时间】:2021-08-01 02:48:37
【问题描述】:
我正在尝试学习 SpringBoot 并尝试制作 API。
我有多个实体如下:
@Entity
public class Superhero {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
}
然后另一个实体是 Superhero_stats - 我想在其中添加其他字段并将其与 SuperHero 实体中的 heroId 映射。
@Entity
@Table(name = "superhero_stats")
public class SuperheroStats {
@Id
@GeneratedValue
private int stats_id;
@OneToOne(mappedBy = "superhero", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
Superhero superhero;
private int intelligence;
}
我的问题是如何在资源中的 data.sql 脚本中编写 sql 查询。我发现很多例子都试图在主应用程序类中做同样的事情,但我也想知道这是否可以通过 data.sql 文件。
这是我正在尝试的示例 data.sql
insert into superhero(name) values ('Spiderman')
insert into superhero(name) values ('Superman')
insert into superhero(name) values ('Batman')
insert into superhero_stats(stats_id, superhero, intelligence) values (1,1,100)
insert into superhero_stats(stats_id, superhero, intelligence) values (2,2,200)
insert into superhero_stats(stats_id, superhero, intelligence) values (3,3,300)
编辑:我在我的应用程序开始时尝试这个。不用于测试。
【问题讨论】:
-
您的问题并不明显,但我假设您正在使用 h2 内存数据库和/或单元测试来测试这个?如果是这样,请参阅此答案:stackoverflow.com/questions/60333899/…。否则,只需安装并使用本地数据库,例如 mysql 或 mariadb。
-
@samoussa.usa 是的,我正在使用 h2。这不适用于单元测试。这是我在应用程序初始启动时所需要的。
标签: spring-boot hibernate jpa h2