我有两个实体,关系是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中通过邮递员创建2个教师对象,我会将它们带到具有特定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"
}
]
}
]
这个课程不是第一个,而是三分之一,为什么?
H2 DATABASE https://i.stack.imgur.com/haoUy.png
答案 0 :(得分:0)
您在两个实体中使用@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