【问题标题】:How to associate nested object (exist in database) with parent object ManyToOne relationship?如何将嵌套对象(存在于数据库中)与父对象多对一关系相关联?
【发布时间】:2023-01-26 14:31:52
【问题描述】:

我想将没有 ID 的 Student 对象保存到数据库中。但是,Student 对象有几个子对象 - 具有 id -。

我怎样才能保存父对象一度无需获取子对象引用并映射到父对象。

public class Student{
//...     
@ManyToOne
@JoinColumn(name = "school_id")
School school;
@ManyToOne
@JoinColumn(name = "course_id")
Course course;
//...
}

和

public class School {
//...     
@OneToMany(mappedBy = "school")
List<Student> students

//...
}

public class Course{
//...     
@OneToMany(mappedBy = "course")
List<Student> students

//...
}

服务层

public Student saveStudent(Student student) {   
 //...
 return studentRepository.save(student);

}

当我尝试保存具有 School 对象的 Student 对象和仅具有 id 属性的 Course 对象时,它会抛出此错误,因为 school 对象没有引用。

对象引用未保存的瞬态实例 - 保存瞬态 冲洗前的实例

如果 School 对象有版本号和 ID 号,它就可以正常工作。

我不想更新或插入新的学校对象。

所以我尝试了 Cascade.ALL、Cascade.MERGE、Cascade.PERSIST,但没有任何效果。 我尝试仅基于 id 覆盖 equals 和 hashCode。不工作。

我的目标是

我的数据库中有几个 School 对象。 当有新学生注册时,Student对象会以School为对象。 最后,我将保存 Student 对象,jpa 将 Student 与 School id 上的 School 相关联。

学生的邮递员邮寄示例。 //失败的请求对象示例 { //... “id”:空, “学校”:{“id”:12}, “课程”:{“id”:21}

 //...

} 
//...

//succesfull request object sample
{
 //...
 "id":null,
 "school":{"id":12, "version": 0},
 "course":{"id":21, "version": 0}

 //...

}

如果学校和课程对象具有版本 (@Version) 属性,则它们会成功合并到学生对象,而无需获取子对象引用和映射到父对象。

第二个帖子请求对象已成功保存,并建立了父子关系。

为什么 jpa 需要版本来合并子和父?

【问题讨论】:

    标签: spring-boot hibernate spring-data-jpa


    【解决方案1】:

    您没有在进行保存的地方显示服务层,但我怀疑您没有将实体附加到学生身上。仅在 POJO 上设置 id 不会使其可用于持久性上下文,这就是您获得此异常的原因。通读 Hibernate 关于持久性上下文的文档 here

    伪服务层实现如下所示:

    public Student saveStudent(Student student) {  // where the student is the object passed in
      School school = schoolRepository.findById(student.getSchool().getId());
      Course course = courseRepository.findById(student.getCourse().getId());
    
      student.setCourse(course);
      student.setSchool(school);
    
      return studentRepository.save(student);
    
    }
    

    【讨论】:

    • 感谢回复。我添加了一些解释。我不想再获取任何引用并将子项映射到父项。如果我将版本属性发布到对象,它将成功合并。
    猜你喜欢
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2019-11-12
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    相关资源
    最近更新 更多