Jesper
Jesper

Reputation: 2814

Foreign key is null after saving objects

I have a relationship between Citizen:

@Entity
@Table(name = "citizens")
public class Citizen {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Size(max = 10, min = 10, message = "CPR must be exactly 10 characters")
private String cpr;

@OneToMany(mappedBy = "citizen", cascade = CascadeType.ALL, orphanRemoval = true)
private List<WeeklyCare> weeklyCare;
}

and WeeklyCare:

@Entity
public class WeeklyCare {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "citizen_id")
private Citizen citizen;
}

I have a REST API that recieves a list of Citizen each with a list of WeeklyCare and saves them:

@Autowired
private CitizenRepository citizenRepository;

@CrossOrigin(origins = "http://localhost:4200")
@PostMapping(path = "/add") // Map ONLY GET Requests
@Secured({"ROLE_ADMIN", "ROLE_DATAMANAGER"})
public ResponseEntity addNewCitizens(
        @RequestBody List<Citizen> citizens) {
    citizenRepository.saveAll(citizens);
    return new ResponseEntity(new ApiResponse(true, "Filen er blevet indlæst", "CITIZENS_SAVED"), HttpStatus.OK);
} 

After this, when I look in the weekly_care table in the database, all rows have null on the citizen_id column. What am I missing?

Upvotes: 3

Views: 51

Answers (1)

StuPointerException
StuPointerException

Reputation: 7267

This is a common scenario in Hibernate and results from not setting the inverse of the relationship:

Citizen c = new Citizen();
WeeklyCare w = new WeeklyCare();
c.getWeeklyCare().add(w);

//The missing link:
w.setCitizen(c);

citizenRepository.save(c);

I'm not sure how this is configured in your web-service request though...

Upvotes: 2

Related Questions