[英]Save entity object with foreign key using CrudRepository
I have two entity classes with @ManyToOne relationship as below.我有两个具有 @ManyToOne 关系的实体类,如下所示。
@Entity
public class Student {
@Id
private Integer studentId;
@Column(nullable = false)
private String studentName;
@ManyToOne(targetEntity = School.class, fetch = FetchType.LAZY, optional = false)
@JoinColumn(referencedColumnName = "schoolId", insertable = false, updatable = false)
private School school;
//Getters and Setters methods
. .
@Entity
public class School {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer schoolId;
@Column(nullable = false)
private String schoolName;
//Getters and Setters methods
When I try to save the student object using CrudRepository default method studentRepository.save(student)
with JSON payload, it gives me an error java.sql.SQLException: Field 'school_id' doesn't have a default value
.当我尝试使用 CrudRepository 默认方法
studentRepository.save(student)
和 JSON 有效负载保存学生对象时,它给了我一个错误java.sql.SQLException: Field 'school_id' doesn't have a default value
。 When I run in the debug mode I can see that the School object is being set correctly.当我在调试模式下运行时,我可以看到 School 对象设置正确。
My JSON payload is as follows:我的 JSON 负载如下:
[
{
"studentId": "2015020",
"studentName": "ABC",
"school": {
"schoolId": 1
}
}
]
I am new to Spring Data JPA, so this might be a very basic mistake.我是 Spring Data JPA 的新手,所以这可能是一个非常基本的错误。
You could try to change the column name collegeId
to schoolId
in table school
, and then modify this line:您可以尝试将表
school
的列名collegeId
更改为schoolId
,然后修改此行:
@ManyToOne(targetEntity = School.class, fetch = FetchType.LAZY, optional = false)
@JoinColumn(referencedColumnName = "schoolId", insertable = false, updatable = false)
private School school;
In the entity Student
the property school
is an object.在实体
Student
,属性school
是一个对象。 To insert new student you must use a reference to school
object.要插入新学生,您必须使用对
school
对象的引用。 So your payload must be like this:所以你的有效载荷必须是这样的:
{
"studentId": 2015020,
"studentName": "ABC",
"school": "http://localhost:8080/api/schools/1"
}
Also you can simplify the definition of the property school
:您也可以简化财产
school
的定义:
@ManyToOne(optional = false)
private School school;
Just check if the name of database column match with entity mapping: If identity column of school table in DB is "school_id", mention it in your mapping:只需检查数据库列的名称是否与实体映射匹配:如果数据库中学校表的标识列是“school_id”,请在映射中提及它:
@Id
@Column(name = "school_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer schoolId;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.