我在这里有一个由三联接表PERSON
维护的ADDRESS
- ADDRESS_TYPE
- PERSON_ADDRESS
关系的数据库。 PERSON
- ADDRESS
关系实际上是一对多关系。
PERSON
ID FIRSTNAME LASTNAME -- --------- -------- 1 John Doe 2 Jane Doe
ADDRESS
ID STREET CITY -- -------------------- ------------- 1 Home Street 1 Hometown 2 Office Street 1 Officetown 3 Main Street 1 Maintown 4 Business Building 1 Businesstown
ADDRESS_TYPE
ID NAME -- --------------- 1 Home Address 2 Office Address
PERSON_ADDRESS
PERSON_ID ADDRESS_TYPE_ID ADDRESS_ID --------- --------------- ---------- 1 1 1 1 2 2 2 1 3 2 2 4
出于实际原因,我希望我的Person
实体最终成为:
public class Person {
private Address homeAddress; // Insertable/updateable by ADDRESS_TYPE_ID=1
private Address officeAddress; // Insertable/updateable by ADDRESS_TYPE_ID=2
}
这是否可以使用JPA 2.0注释?
我已经阅读了Map Key Columns chapter of the JPA wikibook,似乎我必须使用@MapKeyJoinColumn
,但我并不完全清楚如何在这种情况下成功使用它。我希望在它上面看到一个@JoinColumn
示例,但它在wikibook的代码片段中不存在。
如果使用@MapKeyJoinColumn
无法做到这一点,那么在Map<AddressType, Address>
的帮助@MapKeyClass
的情况下也可以使用另一种方法,只要我最终得到getHomeAddress()
getOfficeAddress()
实体中的{}和Person
。
答案 0 :(得分:11)
假设您可以添加其他两个预定义AddressType
,则@MapKeyJoinColumn
的以下方法有效:
public class AddressType {
public static final AddressType HOME = new AddressType(1L, "Home");
public static final AddressType OFFICE = new AddressType(2L, "Office");
...
... hashCode, equals based on id ...
}
public class Person {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinTable(name = "PERSON_ADDRESS",
joinColumns = @JoinColumn(name = "PERSON_ID"),
inverseJoinColumns = @JoinColumn(name = "ADDRESS_ID"))
@MapKeyJoinColumn(name = "ADDRESS_TYPE_ID")
private Map<AddressType, Address> addresses = new HashMap<AddressType, Address>();
...
public Address getHomeAddress() {
return getAddress(AddressType.HOME);
}
public void setHomeAddress(Address a) {
setAddress(AddressType.HOME, a);
}
...
public void setAddress(AddressType type, Address a) {
if (a == null) {
addresses.remove(type);
} else {
addresses.put(type, a);
}
}
public Address getAddress(AddressType type) {
return addresses.get(type);
}
}
因此,您可以通过直接访问地图来使用其他类型的预定义地址类型的预定义方法。 orphanRemoval
用于实现setHomeAddress(null)
行为。 @ElementCollection
在这里不起作用,因为它不支持连接表。