首页 > 解决方案 > 具有相同自动生成 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"
            }
        ]
    }
]

课程编号不是第一个而是第三个,为什么?

H2 数据库 https://i.stack.imgur.com/haoUy.png

标签: javaspringhibernatejpa

解决方案


您在两个实体中都使用 @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


推荐阅读