Save the entity object with the foreign key using CrudRepository

advertisements

I have two entity classes with @ManyToOne relationship as below.

@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

When I try to save the student object using CrudRepository default method studentRepository.save(student) with JSON payload, it gives me an error java.sql.SQLException: Field 'school_id' doesn't have a default value. When I run in the debug mode I can see that the School object is being set correctly.

My JSON payload is as follows:

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

I am new to Spring Data JPA, so this might be a very basic mistake.


You could try to change the column name collegeId to shcoolId in table school, and then modify this line:

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