使用@ManyToMany双向关系传递分离的实体以保持不变

时间:2016-11-27 15:51:00

标签: java spring hibernate jpa spring-data

我很难通过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 to entity转换器...

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保存AEntity(id = null) - 确定

场景2:使用现有BEntity保存AEntity(id = id存在于db中)

方案2中发生以下异常: 一直在stackoverflow中寻找相同的问题,尝试了不同的组合和建议,但没有锁定。

detached entity passed to persist: BEntity; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: BEntity" 

请有人帮忙吗?感谢。

2 个答案:

答案 0 :(得分:0)

你可以试试......

在第二个实体中:

@ManyToMany(cascade=CascadeType.ALL, mappedBy="bentities")
private Set<AEntity> aentities;

在第一个实体中:

@ManyToMany(cascade=CascadeType.ALL) 
@JoinTable(name="bentity_aentities", joinColumns=@JoinColumn(name="aentity_id"), inverseJoinColumns=@JoinColumn(name="bentity_id")) 
private Set<BEntity> bentities;

答案 1 :(得分:0)

终于解决了我的问题。这是DTO to Entity转换器中的问题(我的不好)。

上一个转换器:

public AEntity toAEntity(@NotNull AEntityDto aentityDto) {
     AEntity aentity = new AEntity();
     copyProperties(aentityDto, aentity);
     return aentity;
}

Refactored converter:返回现有实体的引用。

public AEntity toAEntity(@NotNull AEntityDto aentityDto) {
     AEntity aentity = aRepository.findSingleByTitle(aentityDto.getTitle());
     if(aentity == null) {
         aentity = new AEntity();
         copyProperties(aentityDto, aentity);
     }
     return aentity;
}

感谢。

相关问题