[英]CrudRepository, cant save entity with a composite primary key using IdClass
[英]Save entity object with foreign key using CrudRepository
我有兩個具有 @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
當我嘗試使用 CrudRepository 默認方法studentRepository.save(student)
和 JSON 有效負載保存學生對象時,它給了我一個錯誤java.sql.SQLException: Field 'school_id' doesn't have a default value
。 當我在調試模式下運行時,我可以看到 School 對象設置正確。
我的 JSON 負載如下:
[
{
"studentId": "2015020",
"studentName": "ABC",
"school": {
"schoolId": 1
}
}
]
我是 Spring Data 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
是一個對象。 要插入新學生,您必須使用對school
對象的引用。 所以你的有效載荷必須是這樣的:
{
"studentId": 2015020,
"studentName": "ABC",
"school": "http://localhost:8080/api/schools/1"
}
您也可以簡化財產school
的定義:
@ManyToOne(optional = false)
private School school;
只需檢查數據庫列的名稱是否與實體映射匹配:如果數據庫中學校表的標識列是“school_id”,請在映射中提及它:
@Id
@Column(name = "school_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer schoolId;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.