【发布时间】:2016-11-27 15:50:59
【问题描述】:
我很难将实体与 JPA 保持多对多关系(双向)。下面是示例代码:
@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:使用 BEntity (id = null) 保存 AEntity - OK
场景 2:使用现有 BEntity 保存 AEntity(id = db 中存在的 id)
场景2出现以下异常: 一直在 stackoverflow 中寻找相同的问题,并尝试了不同的组合和建议,但没有锁定。
detached entity passed to persist: BEntity; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: BEntity"
有人可以帮忙吗?谢谢。
【问题讨论】:
标签: java spring hibernate jpa spring-data