我無法使用JPA與多對多關係(雙向)持久存在實體。下面是示例代碼:獲取已分離的實體以@ManyToMany雙向關係持續存在
@Entity
@Table(name = "aentity")
public class AEntity {
@Id
@Column(name = "id",
unique = true)
@TableGenerator(initialValue = 1,
name = "aentity_id_generator",
pkColumnName = "table_name",
pkColumnValue = "aentity",
table = "id_generator",
valueColumnName = "id")
@GeneratedValue(generator = "aentity_id_generator",
strategy = GenerationType.TABLE)
private BigInteger id;
@JoinTable(name = "bentity_aentities")
@ManyToMany
private Set<BEntity> bentities;
/* getters and setters follows */
}
@Entity
@Table(name = "bentity")
public class BEntity {
@Id
@Column(name = "id",
unique = true)
@TableGenerator(initialValue = 1,
name = "bentity_id_generator",
pkColumnName = "table_name",
pkColumnValue = "bentity",
table = "id_generator",
valueColumnName = "id")
@GeneratedValue(generator = "bentity_id_generator",
strategy = GenerationType.TABLE)
private BigInteger id;
@ManyToMany(mappedBy = "bentities")
private Set<AEntity> aentities;
/* getters and setters follows */
}
下面是DTO到實體轉換器...
public class DtoToEntityConverter {
public void convertToEntity(AEntityDto aDto, AEntity a) {
a.setBEntities(aDto.getBEntities().parallelStream().
.map(bDto -> {
return toBEntity(bDto); //this will just copy/transfer the properties from bEntityDto to bEntity.
})
.collect(Collectors.toSet()));
}
}
方案1:保存與AEntity BEntity(ID = NULL) - OK
方案2 :使用現有的BEntity(id = id,存在於db中)保存AEntity
場景2中發生以下異常: 在stackoverflo尋找相同的問題w並嘗試了不同的組合和建議,但沒有鎖定。
detached entity passed to persist: BEntity; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: BEntity"
任何人都可以幫忙。謝謝。
謝謝你的迴應,但擁有實體應該是AEntity,沒有「mappedBy」的那個,所以上面的代碼在這種情況下是不合適的,因爲弱實體(具有mappedBy的實體)沒有能力保存/更新擁有實體(在你的情況下是BEntity)。 – imprezzeb