For example I have link entities User and Address
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
}
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@OneToOne(mappedBy = "address")
private User user;
@Column(name = "street")
private String street;
}
How to save correctly in both directions these entities? If i do this: userRepository.save(user); i will have to define address for user, but this address has field "user" and etc... If i do this: addressRepository.save(address); i will have to define user for address, but this user has field "address" and etc...
please show by example
This question about @OneToMany and @ManyToOne. For example :Address a1 = new Address(); Address a2 = new Address(); User user = new User(); user.setAddress(a1, a2, ...)
Should I make: a1.setUser(user); a2.setUser(user) or not? Why Hibernate can't understand, that user.setAddress(a1, a2, ...) means that a1 references to user and a2 references to user?