如何在不修改领域模型的情况下用JPA映射仅含ID列表的多对多关联
问题:如何仅通过注解映射Person的LocationId列表到关联表并生成完整外键
领域模型定义
假设存在独立的Location聚合,代码如下:
class LocationId { String value; } class Location { LocationId value; // 其他属性 }
同时有Person类,可关联0个或多个Location实例,领域模型中Person仅维护LocationId列表,并包含添加/移除Location的方法:
class PersonId { String value; } class Person { PersonId id; List<LocationId> locations; void addLocation(Location location) { // 对location执行校验 // 将location id与person关联 } void removeLocation(Location location) { // 对location执行校验 // 解除location id与person的关联 } }
要求的数据库结构
location表:主键为idperson表:主键为idperson_location关联表:person_id和location_id分别作为外键关联person和location表
待解决的问题
如何仅通过添加注解、不修改领域模型类的方式,将Person的locations属性映射到数据库,同时让person_location表的location_id生成指向location.id的外键?
已尝试的方案
方案1:使用@ElementCollection注解
添加如下注解:
@ElementCollection @CollectionTable( name = "person_location", joinColumns = @JoinColumn(name = "person_id") ) @AttributeOverride(name = "value", column = @Column(name = "location_id"))
问题:生成表时仅创建person_location.person_id到person.id的外键,缺失person_location.location_id到location.id的外键,日志如下:
Hibernate: alter table if exists person_location add constraint FK6ftdgrcrspx1gl3qfvmsdtqru foreign key (person_id) references person
方案2:使用@ManyToMany注解关联完整Location对象
添加如下注解:
@ManyToMany @JoinTable( name = "person_location", joinColumns = @JoinColumn(name = "location_id"), inverseJoinColumns = @JoinColumn(name = "person_id")) private List<Location> locations;
问题:不符合领域模型需求,因为领域模型中不需要在Person中维护完整的Location对象。
内容的提问来源于stack exchange,提问作者Murilo Carlos Cardoso
相关产品推荐
相关产品推荐

