I have the following entities :
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade = CascadeType.ALL)
private Collection<AddressEntity> adresses;
public void addAddresses(Collection<AddressEntity> ad) {
this.addresses = addresses;
addresses.forEach(address-> address.setUser(this));
}
}
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "address")
public class AddressEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "user_id", nullable = false)
private Integer userId;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
private UserEntity user;
}
And I save the entities by calling the userRepository :
users.addAdresses(addresses);
userRepository.saveAll(users);
When the user and the addresses don’t already exist in the database, I have the following error :
ERROR - ERROR: null value in column "user_id" of relation "address" violates not-null constraint
What do I miss here ?