我的实体 stub 如下:
@Entity
public class Company extends AbstractEntity{
private String name;
private String address;
private String zipCode;
private String city;
private String owner;
private String website;
private String emailAddress;
private String phoneNumber;
private String faxNumber;
private List<Category> categories;
private Map<Category, ServiceType> serviceType;
}
如您所见,此处的目标是创建一个映射 ( serviceType
),其中键是另一个集合属性的成员(此处属性为 categories
)。换句话说,我想得到ServiceType
对于 Category
已存储categories
;
Category
是另一个映射实体;
我如何使用注释来实现该目标?
使用Hibernate 4.2.1.Final
最佳答案
如果您在 Company
和 Category
之间有一个联接表,并有一个附加列来提供 ServiceType
,那么您可以通过以下方式实现此目的@ElementCollection
注释。查看this blog post或者在网上搜索更多示例。基本上,您可以在 categories
集合上使用 @OneToMany
或 @ManyToMany
,然后在 map 上使用 @ElementCollection
,像下面这样。
@ElementCollection
// company_id is the column that connects the company table to the join table
@CollectionTable(name = "company_category_servicetypes", joinColumns = @JoinColumn(name = "company_id", insertable=true, updatable=true))
// service_type is the "extra" information you want on the relation, basically the value in the map
@Column(name = "service_type", insertable=true, updatable=true)
// category_id is the other side of the join table (connecting to the category table)
@MapKeyJoinColumn(name = "category_id", insertable=true, updatable=true)
private Map<Category, ServiceType> serviceType;
如果您采用这种方法,我建议您完全摆脱categories
列表。如果多次映射同一个关系/连接表,可能会导致问题和困惑。如果您有一些代码只需要公司的类别,而忽略服务类型,则只需从 serviceType
映射中获取 keySet
即可。
关于java - 当键是使用注释的另一个集合属性成员时,如何映射 "map"属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16984691/