【发布时间】:2020-11-07 18:48:01
【问题描述】:
说明
为了在 hibernate & jpa 中实现多线程,我深度复制了我的一些实体。会话使用这些副本来添加、删除或更新实体。问题
到目前为止它工作得很好,但我遇到了父母/孩子关系的问题。 当我更新我的父母时,它的孩子“总是”被插入......他们永远不会收到任何形式的更新。这非常糟糕,因为我在第二次父更新迭代中收到“重复密钥”异常。我的流程目前如下所示...
- 游戏更新已触发
- 标记为“更新”的深拷贝实体。
- 将这些深拷贝实体传递给更新线程(多线程环境)
- 打开会话,让会话更新它们
- 等待下一次游戏更新并重复循环
亲子
这些类代表子/父关系。
/**
* A component which marks a {@link com.artemis.Entity} as a chunk and stores its most valuable informations.
*/
@Entity
@Table(name = "chunk", uniqueConstraints = {@UniqueConstraint(columnNames={"x", "y"})}, indexes = {@Index(columnList = "x,y")})
@Access(value = AccessType.FIELD)
@SelectBeforeUpdate(false)
public class Chunk extends HibernateComponent{
public int x;
public int y;
public Date createdOn;
@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "chunk_identity", joinColumns = @JoinColumn(name = "identity_id"), inverseJoinColumns = @JoinColumn(name = "id"), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@Fetch(FetchMode.JOIN)
@BatchSize(size = 50)
public Set<Identity> inChunk = new LinkedHashSet<>();
@Transient
public Set<ChunkLoader> loadedBy = new LinkedHashSet<>();
public Chunk() {}
public Chunk(int x, int y, Date createdOn) {
this.x = x;
this.y = y;
this.createdOn = createdOn;
}
}
/**
* Represents a ID of a {@link com.artemis.Entity} which is unique for each entity and mostly the database id
*/
@Entity
@Table(name = "identity")
@Access(AccessType.FIELD)
@SQLInsert(sql = "insert into identity(tag, typeID, id) values(?,?,?) ON DUPLICATE KEY UPDATE id = VALUES(id), tag = values(tag), typeID = values(typeID)")
@SelectBeforeUpdate(value = false)
public class Identity extends Component {
@Id public long id;
public String tag;
public String typeID;
public Identity() {}
public Identity(long id, String tag, String typeID) {
this.id = id;
this.tag = tag;
this.typeID = typeID;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
var identity = (Identity) o;
return id == identity.id;
}
@Override
public int hashCode() {
return Objects.hash(id, tag, typeID);
}
}
问题
知道为什么我的深层克隆父母总是插入它的孩子吗?以及如何在仍然使用多线程的同时防止这种情况(当我不使用克隆对象时,会发生休眠内部异常)...【问题讨论】:
标签: java spring multithreading hibernate jpa