我有2个简单的实体:学生和班级。我想发布一个学生,在其中指定其所属的班级,但是我陷入了休眠映射中。
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)
StudentModel
@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);
}
...
但是当我向邮递员提出以下要求的请求时:
{
"name": "some name",
"age": 12,
"class_id": 1
}
我从休眠中收到以下错误:
Column 'class_id' cannot be null
我的休眠映射在哪里出错?
答案 0 :(得分:2)
这就是我在休眠状态下加入工作的方式。看看:
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列表。
答案 1 :(得分:1)
错误在这一行:
"class_id": 1
您使用的是列名,而不是字段名。您必须将class_id
替换为classModel
,其中classModel
是一个对象。其他解决方案是从json中按ID查找ClassModel
,并将其设置为StudentModel
的父项。