Spring数据JDBC多对多关系管理

Spring Data JDBC many to many relationship management

我有一个多对多的关系 person -> person_address <- address and use a reference class。但是在我的 Person 聚合根中,它似乎只添加 person_address 有效(地址集合):

@MappedCollection(idColumn = "PERSON_ID")
private Set<PersonAddress> addresses;

public void addAddress(final Address address) {
    Assert.notNull(getId(),"Person ID cannot be null");
    Assert.notNull(address.getId(),"Address ID cannot be null");
    addresses.add(new PersonAddress(address.getId()));
}

我希望能够从地址集合中删除然后保存,但这不起作用。所以我改用:

@Modifying
@Query(value = "delete from person_address where person_id = :personId and address_id = :addressId")
void deletePersonAddressById(@Param("personId") final Long personId, final Long addressId);

这是处理此问题的最佳方法吗?

@ToString
@EqualsAndHashCode
@Getter
@Setter
public class PersonAddress {

    /**
     * Timestamp generated by database.
     */
    @ReadOnlyProperty
    @Setter(AccessLevel.NONE)
    private LocalDateTime created;

    private Long addressId;

    public PersonAddress(final Long addressId) {
        this.addressId = addressId;
    }
}

您应该能够从 Person.addresses 中删除条目并再次保存该实体。

I created a sample to demonstrate this on GitHub.

我过去掉进的陷阱是没有为 PersonAddress 正确实现 equalshashCode,这当然很重要,当你想从HashSet 或类似的。