OneToMany relationship doesn't save id of owner entity in secondary entity

55 Views Asked by At

Im trying to save in postgres 2 entities, Configuration and Screen. Configuration can have many Screens, then is oneToMany, and one Screen can have one Configuration, then ismanyToOne. I'm using JPA to save those entities. The problem I have is, in Screen table, configuration_id relationship is not saved. That's my code:

@Data
public class Configuration  {

@Id
private String id = UUID.randomUUID().toString();

@OneToMany(mappedBy = "id_configuration", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Screen> screen;

And this other

@Table
@Entity
@Data
public class Screen {

private String status;

@JoinColumn(name = "configuration_id")
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Configuration configuration;

when I create a new Configuration, I indicate the Screen that should be created except the 'id' field (it's configuration id created randomlly)

The data is saved well, both in Configuration and Screen, except for that (id_configuration) field. There is a configuration_id field in Screen table, but it is always empty and never filled. Why is this happening? I'm indicating the cascade type ALL, and relationships are well-formed.

1

There are 1 best solutions below

2
Lukier On

Due to tutorials like: https://www.baeldung.com/hibernate-one-to-many

I guess the problem in your model is mappedBy in @OneToMany. In your case it should point to class field which mapping this relation.

So it should be: @OneToMany(mapped_by = "configuration", ...)