gpt4 book ai didi

java - Hibernate 无法将许多学生映射到一个类(class)

转载 作者:行者123 更新时间:2023-12-01 19:40:16 26 4
gpt4 key购买 nike

我有 2 个简单的实体:学生和类(class)。我想发布一个学生,在其中指定它所属的类(class),但我陷入了 hibernate 映射。

ClassModel.class

@Entity
@Table(name = "class" )
public class ClassModel implements Serializable {


@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@NotEmpty
@Size(max = 20)
@Column(name = "name")
private String name;

@Column(name = "tables")
private int tables;

@Column(name = "chairs")
private int chairs;

@Column(name = "teacher")
private String teacher;
(getters + setters)

学生模型

@Entity
@Table(name = "student")
public class StudentModel implements Serializable {

@Id
@Column(name = "student_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int student_id;

@NotEmpty
@Column(name = "name")
@Size(max = 50)
private String name;

@Column(name = "age")
private int age;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private ClassModel classModel;
(getters + setters)
}

StudentController.java

...
@Autowired
private StudentService studentService;

@Autowired
private ClassService classService;

@PostMapping(value = "/save")
public StudentModel save(@RequestBody StudentModel studentModel){
ClassModel classModel = classService.findById(studentModel.getClassId()).get();
studentModel.setClassModel(classModel);
return studentService.save(studentModel);
}
...

但是当我用以下正文向 Postman 发出请求时:

{
"name": "some name",
"age": 12,
"class_id": 1
}

我从 hibernate 中收到以下错误:

Column 'class_id' cannot be null

我的 hibernate 映射错误在哪里?

最佳答案

这就是我在 hibernate 状态下进行工作连接的方式。看看:

TrainingEntity.java

@Id
private Integer id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "animal_id", nullable = false, insertable = false, updatable = false)
private AnimalEntity animalEntity;

@Column(name = "animal_id")
private Integer animalId;

AnimalEntity.java

@Id
private Integer id;

@OneToMany(mappedBy = "animalEntity", fetch = FetchType.LAZY)
private List<TrainingEntity> trainingEntityList = new ArrayList<>();

这里是 AnimalEntity 和 TrainingEntity 之间的连接。AnimalEntity 有一个 TrainingEntities 列表。

关于java - Hibernate 无法将许多学生映射到一个类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55581311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com