春季数据JDBC许多关系管理
我有一个众多的关系人 - > 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该只能从
person.addresses
中删除条目,然后再次保存实体。我创建了一个示例来在github上证明这一点。
我过去遇到的陷阱是不正确地实现
equals
和hashcode
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
andhashCode
forPersonAddress
, which is of course important, when you want to remove instances from aHashSet
or similar.