2017-03-25 65 views
0

我有兩個實體類,它們具有@ManyToOne關係,如下所示。用外鍵使用CrudRepository保存實體對象

@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 
     } 
    } 
] 

我是新來的春天JPA的數據,所以這可能是一個非常基本的錯誤。

回答

0

你可以嘗試在表school列名collegeId更改爲shcoolId,然後修改此行:

@ManyToOne(targetEntity = School.class, fetch = FetchType.LAZY, optional = false) 
@JoinColumn(referencedColumnName = "schoolId", insertable = false, updatable = false) 
private School school; 
+0

感謝您指出。這是一個錯字,我糾正了它。 – anirus

0

在實體Student財產school是一個對象。要插入新學生,您必須使用對school對象的引用。所以,你的有效載荷必須是這樣的:

{ 
    "studentId": 2015020, 
    "studentName": "ABC", 
    "school": "http://localhost:8080/api/schools/1" 
} 

還可以簡化財產school定義:

@ManyToOne(optional = false) 
private School school; 
0

只是檢查,如果數據庫列匹配的名稱與實體映射: 如果標識列DB中的學校表是「school_id」,請在您的地圖中提及:

@Id 
    @Column(name = "school_id") 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Integer schoolId; 
相關問題