春季数据JDBC许多关系管理

发布于 2025-01-30 17:22:15 字数 1093 浏览 3 评论 0原文

我有一个众多的关系人 - > Person_Address< - 地址并使用参考类。但是在我的人中,似乎只添加Person_Address Works(地址集合):

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

I have a many-to-many relationship person -> person_address <- address and use a reference class. But in my Person aggregate root it seems only adding person_address works (addresses collection):

@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()));
}

I want to be able to delete from addresses collection and then do a save, but this doesn't work. So instead I use:

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

Is this the best way to handle this?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

唐婉 2025-02-06 17:22:15

您应该只能从person.addresses中删除条目,然后再次保存实体。

我创建了一个示例来在github上证明这一点。

我过去遇到的陷阱是不正确地实现equalshashcode prethaDdress当然很重要,当您想尝试时,这一点很重要。从hashset或类似内容中删除实例。

You should be able to just remove entries from Person.addresses and save the entity again.

I created a sample to demonstrate this on GitHub.

On pitfall I fell into in the past was to not properly implement equals and hashCode for PersonAddress, which is of course important, when you want to remove instances from a HashSet or similar.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文