java - 当键是使用注释的另一个集合属性成员时,如何映射 "map"属性?

标签 java hibernate mapping hibernate-annotations

我的实体 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

最佳答案

如果您在 CompanyCategory 之间有一个联接表,并有一个附加列来提供 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/

相关文章:

java - 如何将 log4j 输出消息分配给变量

java - firebase.auth.PhoneAuthProvider 缺失

java - hibernate @Formula/错误 : schema "FOO" does not exist

java - 简单的 map 投影

c# - NHibernate 转换问题(怀疑原因是不正确的映射)

sql - SQL弱关联表字段映射

java - 解析字符串以获取分组参数

java - java中的字符串数组给出错误

hibernate - JPA:如何使用HQL检查NULL查询参数值?

java - Hibernate 3 不自动创建表