简体   繁体   中英

Foreign key is null : Hibernate Spring

I try to save object Run to database. I defined relation between Run and City. One city could have many runs. I got problem with city_id. Is null.

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'city_id' cannot be null

My entieties and controller: City

@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "cities")
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "city_id")
    private long id;
    @OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Run> runs = new ArrayList<>();
    private String name;
}

Run

@Entity
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "runs")
public class Run {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name = "name_run")
    private String nameRun;
    @Column(name = "distance")
    private double distance;
    @Column(name = "date")
    private Date date;
    @Column(name = "my_time")
    private String myTime;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "city_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private City city;
}

Controller


@CrossOrigin
@RestController
@RequestMapping("/api/")
public class RunController {

    private RunRepository runRepository;
    private RunService runService;

    public RunController(RunRepository runRepository, RunService runService) {
        this.runRepository = runRepository;
        this.runService = runService;
    }

    @GetMapping("runs")
    public ResponseEntity<List<Run>> getRuns() {
        return runService.getRuns();
    }

    @PostMapping("runs")
    public ResponseEntity addRun(@RequestBody Run run) {

        return new ResponseEntity<>(runRepository.save(run), HttpStatus.OK);
    }
}

I would like to save the run in DB. My test request looks like :

{ "nameRun": "test", "distance":"5.0", "date":"2020-12-12", "myTime":"50:40", "city":"test1" }

Result from evaluate expresion in Intelijj:

在此处输入图片说明

Why the City = null? Is here error in mapping?

Can you try with this json but you need to pass city id in json.

{
    "nameRun": "test",
    "distance": "5.0",
    "date": "2020-12-12",
    "myTime": "50:40",
    "city": {
        "id": 1,
        "name": "test1"
    }
}

Thanks

First of all, use Long for id please. It is better to add @Entity annotation too.

@Entity
public class City {

    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Run> runs = new ArrayList<>();

}

@Entity
public class Run {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private City city;

}

You need to set city_id when you save Run .

The simplest way to do that is just create a fake transient City and set id to it.

City city = new City();
city.setId(1L);

Run run = new Run();
run.setCity(city);

repository.save(run);

Obviously you should have a city with id 1L in the database.

Other options are

  1. Use something like session.load() Hibernate analogue with Spring repository to create City without loading it from datatbase.
  2. Load City entity entirely by id.

if you wanna save any run class,

Run run = new Run();
City city = new City();
city.getRuns().add(run);
runRepository.save(run);

if you wanna save any run class, first you need to insert to (Arraylist) runs variable of city class like city.getRuns().add(run) after filling run then you can runRepository.save(run).

Also my samples are here. You can look at myclasses.

First class is called Patient .

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@ToString
@Table(name = "aapatient")
public class Patient {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AA_PATIENT_SEQ")
    @SequenceGenerator(sequenceName = "AA_PATIENT_SEQ", allocationSize = 1, name = "AA_PATIENT_SEQ")
    @Column(name = "patientid")
    private Long patientid;
    private String name;
    private String lastname;  

    @OneToMany(mappedBy = "patient", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Problem> problems; 
}

Second Class called Problem is this one.

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(name="aaproblem")
public class Problem{

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AA_PATIENT_SEQ")
    @SequenceGenerator(sequenceName = "AA_PATIENT_SEQ", allocationSize = 1, name = "AA_PATIENT_SEQ")
    @Column(name = "problemid")
    private Long problemid;
    private String problemName;
    private String problemDetail; 

    @Temporal(TemporalType.TIMESTAMP)
    Date creationDate;

    @NotNull
    @ManyToOne(optional = true, fetch = FetchType.LAZY)
    @JoinColumn(name = "patient_id")
    private Patient patient;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM