0

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?

PapaG
  • 11
  • 1
  • 1
    It's better if you explore things on own. Set the `show_sql` parameter. You can refer https://stackoverflow.com/questions/30890076/spring-boot-show-sql-parameter-binding Try out the repo.save(user) or address and see the SQL. You will learn it faster – Chetan Ahirrao May 01 '23 at 16:48
  • you need to set both properties before saving there is no other way, and also check do you really need bidirectional mapping, it may cause some issues because of circular reference – deadshot May 01 '23 at 17:25
  • Save one, set the relationships, then save the other. In this case, you need Address saved first as User needs the ID to set in its FK column. Or you can create both, set references and just call save on User as the cascade persist option on the reference will cause JPA to pick up and save your address too. This is covered in most JPA tutorials though, so not really a good question for stack overflow – Chris May 01 '23 at 22:35

1 Answers1

0

You can create a public method in your User class just like:

public void setAdress(Address adress) {
   this.address = adress;
   adresss.user = this;
}

I believe this should work