woelfle
woelfle

Reputation: 557

How to map a Map of Sets in JPA

Is there a way in JPA to map an attribute with type Map<String, Set<Address>>

Given the following classes:

class Company {
  int id;
  Map<String, Set<Address>> addresses; // Key is the country of the Address
}

class Address {
  int id;
  String country;
}

There are three tables:

tbl_company
  id INT

tbl_address
  id INT
  country VARCHAR(40)

tbl_company_address
  company_id INT
  address_id INT

How can I map this scenario with JPA

Upvotes: 2

Views: 642

Answers (1)

Art Licis
Art Licis

Reputation: 3679

One of possible solutions is having an address-wrapping class, and insert Set into that class. In that case you will be able to use map (using @OneToMany, @MapKey annotations). E.g.

@OneToMany(mappedBy = ...)
@MapKey(name = "countryKey")
private Map<String, AddressWrapper> addressWrappers;

.. and AddressWrapper would contain @OneToMany Set<Address> addresses;, along with String countryKey.

Upvotes: 1

Related Questions