使用CrudRepository使用外键保存实体对象

时间:2017-03-25 03:26:30

标签: java json hibernate jpa spring-data

我有两个@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

当我尝试使用带有JSON有效负载的CrudRepository默认方法studentRepository.save(student)保存学生对象时,它会给我一个错误java.sql.SQLException: Field 'school_id' doesn't have a default value。当我在调试模式下运行时,我可以看到正确设置了School对象。

我的JSON有效负载如下:

[
    {
      "studentId": "2015020",
      "studentName": "ABC",
      "school": {
        "schoolId": 1
      }
    }
]

我是Spring Data JPA的新手,所以这可能是一个非常基本的错误。

3 个答案:

答案 0 :(得分:0)

您可以尝试将表using System; using System.Collections.Generic; using System.Linq; namespace blogging.Infrastructure { public class RoleProvider: System.Web.Security.RoleProvider { } } 中的列名collegeId更改为shcoolId,然后修改此行:

school

答案 1 :(得分:0)

在实体Student中,属性school是一个对象。要插入新学生,您必须使用对school对象的引用。所以你的有效载荷必须是这样的:

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

您还可以简化属性school的定义:

@ManyToOne(optional = false)
private School school;

答案 2 :(得分:0)

只需检查数据库列的名称是否与实体映射匹配: 如果DB中的学校表的标识列是" school_id",请在映射中提及:

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