java 如何在JPA中保存链接实体

ldfqzlk8  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(109)

例如,我有链接实体User和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;
}

如何在两个方向上正确保存这些实体?如果我这样做:userRepository.save(user);我必须为用户定义地址,但此地址具有字段“用户”等...如果我这样做:addressRepository.save(address);我必须为address定义user,但此用户具有字段“address”等...
请举例说明
关于@OneToMany和@ManyToOne的问题。例如:Address a1 = new Address();int getName = new int();String getString();setAddress(a1,a2,...)
我应该做:sort();a2.setUser(user)或否?为什么Hibernate不能理解,user.setAddress(a1,a2,...)意味着a1引用user,a2引用user?

2vuwiymt

2vuwiymt1#

你可以在User类中创建一个公共方法,就像这样:

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

我相信这应该行得通

相关问题