我的实体:
@Entity
public class Document {
@Id
protected String id; //It string in purpose
@OneToOne(cascade = ALL)
@JoinColumn(name = "DOCUMENT_DETAILS")
private DocumentDetails details;
}
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "documentDiscr")
@EqualsAndHashCode
public abstract class DocumentDetails {
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private Money total;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "SELLER_ID")
private Company seller;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "BUYER_ID")
private Company buyer;
}
@Entity
public class Company {
@Id
protected String id;
private String name;
private String phoneNumber;
private String email;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id")
private Address address;
}
@Entity
@EqualsAndHashCode
public class Address {
@Id
@GeneratedValue(strategy= GenerationType.SEQUENCE)
private Long id;
private String country;
private String city;
private String postalCode;
private String streetName;
private String streetNumber;
private String apartmentNumber;
}
@Path("path")
@Transactional
public class MyResource {
@Inject
MyRepo myRepo;
@PUT
public Document updateDoc(Document document){
myRepo.update(document);
}
}
public class Repo<T extends MyClass> implements MyRepo<T> {
@PersistenceContext
protected EntityManager entityManager;
public T create(T t) {
t.generateId();
this.entityManager.persist(t);
return t;
}
public T update(T entity) {
return entityManager.merge(entity);
}
}
当我调用entityManage.update(documentEntity)并将同一公司作为供应商和买家添加时,我看到了
‘同一实体的多重表示’.
我读了this,但没有任何帮助.当我删除CascadeType.All我得到
‘分离的实体传递给persist:my.pckg.Address’
我也尝试删除CascadeType.Merge但错误是一样的.
我可以做什么?我的错误在哪里?
UPDATE
首先,我将@ManyToOne(Cascade.All)更改为DocumentDetails中的@ManyToOne()
其次,我将@ManyToOne(Cascade.All)更改为DocumentDetails中的@ManyToOne(Cascade.Merge).
第三,我在DocumentDetails中将@ManyToOne(Cascade.All)更改为@ManyToOne(除了all和merge之外的所有类型).
我也尝试使用Address类
最佳答案 好的 – 从Piotr Gwiazda的提示我解决了它.
添加简单而天真的解决方案:
if(seller != null && buyer != null){
if(seller.equals(buyer)){
document.getDetails.setSeller(document.getDetails().getBuyer());
}
}
(更好的答案是SpringData)
在update()之前.这种情况已经到位,因为当两个不同的对象相等但它们引用不同时,hibernate无法将它们作为同一个对象处理.