jpa 使用CrudRepository保存具有外键的实体对象

iih3973s  于 2022-11-14  发布在  其他
关注(0)|答案(3)|浏览(193)

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

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

pu3pd22g

pu3pd22g1#

在实体Student中,属性school是一个对象。要插入新学生,必须使用对school对象的引用。因此,有效负载必须如下所示:

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

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

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

wn9m85ua2#

只需检查数据库列的名称是否与实体Map匹配:如果DB中school表的标识列是“school_id”,请在Map中提及它:

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

rhfm7lfc3#

您可以尝试将表school中的列名collegeId更改为schoolId,然后修改此行:

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

相关问题