java - 具有相同自动生成 ID 的两个表
问题描述
我有两个具有 OneToMany/ManyToOne 关系的实体
老师
@Entity
@JsonIgnoreProperties({"password"})
public class Teacher extends ResourceSupport{
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "teacher")
private List<Course> courses;
@JsonCreator
public Teacher(@JsonProperty("Username") String username
,@JsonProperty("Password") String password){
this.username = username;
this.password = password;
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
public String getUsername(){
return username;
}
public String getPassword(){
return password;
}
@Setter
private String username;
@Setter
private String password;
Teacher(){
}
}
课程实体
@Entity
@NoArgsConstructor
@JsonIgnoreProperties({"teacher"})
public class Course {
@Getter @GeneratedValue(strategy = GenerationType.AUTO) @Id private Long identifier;
@Getter @Setter @NotNull private String name;
@Getter @Setter @NotNull private String description;
@Getter @Setter @ManyToOne private Teacher teacher;
@JsonCreator
public Course(@JsonProperty("Name") String name , @JsonProperty("Description") String description , @JsonProperty("Teacher")Teacher teacher){
this.description = description;
this.name = name;
this.teacher= teacher;
}
}
如果我在 PostRequest 中通过 Postman 创建了 2 个 Teachers 对象,并且我将它们放在具有特定 ID 的桌子上。
但是当我创建一门课程时,它不会以 id 1 开头,它需要最后一个教师 id 并从那里开始。
这就是我得到的
[
{
"courses": [
{
"identifier": 3,
"name": "java",
"description": "java basico"
}
],
"username": "teuddy",
"links": [
{
"rel": "self",
"href": "http://localhost:8181/teachers/teuddy"
}
]
},
{
"courses": [],
"username": "rafael",
"links": [
{
"rel": "self",
"href": "http://localhost:8181/teachers/rafael"
}
]
}
]
课程编号不是第一个而是第三个,为什么?
解决方案
您在两个实体中都使用 @GeneratedValue(strategy = GenerationType.AUTO) 和 @GeneratedValue ,它们默认为 GenerationType.AUTO 。这意味着确定了适用于所用 DB 的 ID 生成器。如果是一个全局序列的 H2 数据库。所以所有实体共享这个序列来生成 id。
还有其他策略,但 H2 不支持 afaik IDENTITY 并且也回退到 SEQUENCE。
如果实体不共享其 ID 对您很重要,您可以尝试 TABLE 策略,但我不建议这样做。(有关更多信息,请阅读Why-you-should-never-use-the-table-identifier-generator-with-jpa-and-hibernate
推荐阅读
- entity-framework-core - 如果您尝试包含的属性为 null,则在 Entity Framework Core 2.0 中调用 Include 会使实体为 null
- macos - 通过自制软件安装的任何东西都会抛出“找不到命令”
- sql - Sql select - 如果为空,如何从其他表中选择
- bash - 文件消失而不是重命名
- node.js - 找不到模块'source-map-support/register
- python - Keras:模型预测,检查输入形状时出错
- javascript - 如何用相同代码的扩展片段替换代码字符串中的“特殊”字符?
- docker - Docker-Compose:如何等待其他服务准备好?
- r - 在 dplyr 中的列表中求和
- javascript - JSX 错误:“JSX.IntrinsicElements”类型上不存在属性