问题描述
我有一个多对多关系,其中链接表具有附加属性.因此,链接表也由实体类表示,并称为Composition
. Composition
的主键是链接到相应实体(例如)的@Embeddable
. 2个@ManyToOne
参考.
I have a many-to-many relationship where the link table has an additional property. Hence the link table is represented by an entity class too and called Composition
. The primary key of Composition
is an @Embeddable
linking to the according entities, eg. 2 @ManyToOne
references.
用户可能会在选择两个引用中的任何一个时出错,因此必须更新复合主键.但是,由于JPA(休眠)的工作方式,这当然总是会创建一个新行(插入)而不是进行更新,并且旧的Composition
仍然会存在.最终结果是添加了新行,而不是对其进行更新.
It can happen that a user makes an error when selecting either of the 2 references and hence the composite primary key must be updated. However due to how JPA (hibernate) works this will of course always create a new row (insert) instead of an update and the old Composition
will still exist. The end result being that a new row was added instead of one being updated.
选项1:
旧的Composition
可以在插入新的Composition
之前删除,但这将要求处理此问题的相应方法同时需要新的和旧的版本.另外,由于更新的版本实际上是一个新的实体,因此乐观锁定将不起作用,因此上一次更新将始终获胜.
The old Composition
could just be deleted before the new one is inserted but that would require that the according method handling this requires both the old and new version. plus since the updated version is actually a new entity optimistic locking will not work and hence last update will always win.
选项2:
本地查询.该查询还会增加版本列,并在WHERE子句中包含版本.如果更新计数为0(并发修改或删除),则抛出OptimisticLockException
Native query. The query also increments version column and includes version in WHERE clause. Throw OptimisticLockException
if update count is 0 (concurrent modification or deletion)
什么是更好的选择?解决此问题的通用方法"是什么?
What is the better choice? What is the "common approach" to this issue?
推荐答案
为什么不只是将Composition
的主键更改为自动生成的UID?然后,用户可以更改对要连接的实体的两个引用,而不必删除/重新创建Composition
实体.然后将保持乐观锁定.
Why not just change the primary key of Composition
to be a UID which is auto-generated? Then the users could change the two references to the entities being joined without having to delete/re-create the Composition
entity. Optimistic locking would then be maintained.
例如:
@Entity
@Table(name = "COMPOSITION")
public class Composition {
@Id
@Column(name = "ID")
private Long id; // Auto-generate using preferred method
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn( .... as appropriate .... )
private FirstEntity firstEntity;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn( .... as appropriate .... )
private SecondEntity secondEntity;
....
这篇关于JPA @EmbeddedId:如何更新复合主键的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!