Java 使用CRUDEPository使用外键保存实体对象
我有两个具有@manytone关系的实体类,如下所示Java 使用CRUDEPository使用外键保存实体对象,java,json,hibernate,jpa,spring-data,Java,Json,Hibernate,Jpa,Spring Data,我有两个具有@manytone关系的实体类,如下所示 @Entity public class Student { @Id private Integer studentId; @Column(nullable = false) private String studentName; @ManyToOne(targetEntity = School.class, fetch = FetchType.LAZY, optional = false) @JoinColum
@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
当我尝试使用带有JSON有效负载的CRUDepository默认方法studentRepository.save(student)
保存student对象时,它会给我一个错误java.sql.SQLException:字段“school\u id”没有默认值
。在调试模式下运行时,我可以看到学校对象设置正确
我的JSON负载如下所示:
[
{
"studentId": "2015020",
"studentName": "ABC",
"school": {
"schoolId": 1
}
}
]
我不熟悉Spring数据JPA,因此这可能是一个非常基本的错误。您可以尝试将表
school
中的列名collegeId
更改为schoolId
,然后修改此行:
@ManyToOne(targetEntity = School.class, fetch = FetchType.LAZY, optional = false)
@JoinColumn(referencedColumnName = "schoolId", insertable = false, updatable = false)
private School school;
在实体
Student
中,属性school
是一个对象。要插入新学生,必须使用对学校
对象的引用。因此,您的有效载荷必须如下所示:
{
"studentId": 2015020,
"studentName": "ABC",
"school": "http://localhost:8080/api/schools/1"
}
您还可以简化属性学校的定义
:
@ManyToOne(optional = false)
private School school;
只需检查数据库列的名称是否与实体映射匹配: 如果DB中学校表的标识列是“学校id”,请在映射中提及它:
@Id
@Column(name = "school_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer schoolId;
谢谢你指出这一点。这是个打字错误,我已经改正了。
@Id
@Column(name = "school_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer schoolId;