Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用CRUDEPository使用外键保存实体对象_Java_Json_Hibernate_Jpa_Spring Data - Fatal编程技术网

Java 使用CRUDEPository使用外键保存实体对象

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

我有两个具有@manytone关系的实体类,如下所示

@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;