Antoniossss
Antoniossss

Reputation: 32507

How to map a "map" property in case when keys are another collection property members using annotations?

I have entity stub as follows:

@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;

}

As you can see, the goal here is to create a map (serviceType) with keys being members of another collection property (here the property is categories). In other words, I want to get ServiceType for Category stored categories; Category is another mapped entity; How can i achieve that goal using annotations? Using Hibernate 4.2.1.Final

Upvotes: 0

Views: 44

Answers (1)

Jeff Evans
Jeff Evans

Reputation: 1297

If you have a join table between Company and Category, with an additional column to give the ServiceType, then you can achieve this with @ElementCollection annotation. Check out this blog post or search the web for more examples. Basically, you can use @OneToMany or @ManyToMany on the categories collection, then @ElementCollection on the map, something like the following.

@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;

I recommend if you take this approach that you get rid of the categories list entirely. It can cause problems and confusion if the same relation/join table is mapped multiple times. If you have some code that ever just wants the categories for a company, ignoring the service type, you can just get the keySet from the serviceType map instead.

Upvotes: 1

Related Questions