2016-11-27 30 views
0

我無法使用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" 

任何人都可以幫忙。謝謝。

回答

0

你可以試試...

在第二個實體:

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

在第一個實體:

@ManyToMany(cascade=CascadeType.ALL) 
@JoinTable(name="bentity_aentities", [email protected](name="aentity_id"), [email protected](name="bentity_id")) 
private Set<BEntity> bentities; 
+0

謝謝你的迴應,但擁有實體應該是AEntity,沒有「mappedBy」的那個,所以上面的代碼在這種情況下是不合適的,因爲弱實體(具有mappedBy的實體)沒有能力保存/更新擁有實體(在你的情況下是BEntity)。 – imprezzeb

0

終於解決了我的問題。這是DTO到實體轉換器(我的壞)的問題。

上一頁轉換器:

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

重構轉換器:返回現有實體的引用。

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

謝謝。

相關問題