我对我的项目印象非常深刻,但突然之间我注意到我做了一些非常错误的事情,因为,每次创建,合并,删除我都在手动做,但是我应该让JPA为我做好照顾?
我所做的是创建数据库,然后从中创建实体。所以here is my database所以你们可以理解我的概念问题。
以一种简单的方式:
user
只有address
,只有一个地址。此address
由city
,state
和country
组成。我希望能够通过级联创建,更新user address
。
我认为由JPA生成的映射是错误的(或者我的理解是错误的),让我说明一下:
public class User {
..
//bi-directional many-to-one association to UserAddress
@ManyToOne(cascade = CascadeType.ALL) // should be one to one ?
@JoinColumn(name="id_user_address")
private UserAddress userAddress;
..
}
public class UserAddress {
..
//bi-directional many-to-one association to User
@OneToMany(mappedBy="userAddress", fetch=FetchType.EAGER)
private List<User> users;
//bi-directional many-to-one association to AddressCity
@ManyToOne
@JoinColumn(name="id_city")
private AddressCity addressCity;
//bi-directional many-to-one association to AddressState
@ManyToOne
@JoinColumn(name="id_state")
private AddressState addressState;
//bi-directional many-to-one association to AddressCountry
@ManyToOne
@JoinColumn(name="id_country")
private AddressCountry addressCountry;
..
}
我认为user
有one adress only
,所以应该OneToOne
映射?
关于UserAdress
,country
和state
的{{1}}也是如此。
答案 0 :(得分:1)
如果您想在同一地址允许多个用户@ManyToOne就是您想要的。如果您使用@OneToOne,则每个地址只能有一个用户。