【问题标题】:Save entity object with foreign key using CrudRepository使用 CrudRepository 使用外键保存实体对象
【发布时间】:2017-08-18 03:21:35
【问题描述】:

我有两个具有@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 的新手,所以这可能是一个非常基本的错误。

【问题讨论】:

    标签: java json hibernate jpa spring-data


    【解决方案1】:

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

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

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

    @ManyToOne(optional = false)
    private School school;
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 感谢您指出。这是一个错字,我已经更正了。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-02
        • 1970-01-01
        • 2011-05-01
        • 2016-08-21
        相关资源
        最近更新 更多