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 ?
@Column(name = "user_id", nullable = false)
private Integer userId;
Above code is creating the problem here. You can remove the userId
field of AddressEntity
as it is not required. JoinColumn
annotation added on user field of AddressEntity
creates user_id
column and saves id
of UserEntity
.
You can read more about JoinColumn
annotation here - https://www.baeldung.com/jpa-join-column.
I executed the following code after removing the userId
field from AddressEntity
, and I get the below results.
UserEntity user1 = new UserEntity();
UserEntity user2 = new UserEntity();
List<AddressEntity> addresses1 = List.of(new AddressEntity(), new AddressEntity());
List<AddressEntity> addresses2 = List.of(new AddressEntity(), new AddressEntity());
user1.addAddresses(addresses1);
user2.addAddresses(addresses2);
userRepository.saveAll(List.of(user1, user2));
User Table:
ID |
---|
1 |
2 |
Address Table:
ID | USER_ID |
---|---|
1 | 1 |
2 | 1 |
3 | 2 |
4 | 2 |