简体   繁体   English

一对多关系中的CascadeType问题

[英]CascadeType problem in One to Many Relation

I have two classes which have a Unidirectional One to Many relation with each other. 我有两个类,它们之间具有单向一对多关系。

public class Offer{
    ...
    @OneToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "Offer_Fields",
    joinColumns =
    @JoinColumn(name = "OFFER_ID"),
    inverseJoinColumns =
    @JoinColumn(name = "FIELDMAPPER_ID"))
    private Set<FieldMapper> fields = new HashSet<FieldMapper>();
}


@Entity
@Table(name = "FieldMapper")
public class FieldMapper implements Serializable {
   @Id
   @Column(name = "FIELDMAPPER_ID")
   @GeneratedValue
   private int id;
   @OneToOne(cascade=CascadeType.ALL)
   @JoinColumn(name = "multilingual_field_fk")
   private MultiLingual field;
   @OneToOne(cascade=CascadeType.ALL)
   @JoinColumn(name = "multilingual_value_fk")
   private MultiLingual value;
}

I want to store an Offer with a set of FieldMapper to database. 我想将具有一组FieldMapper的商品存储到数据库中。 When I Use CascadeType.ALL in my OneToMany, I got this error: 当我在OneToMany中使用CascadeType.ALL时,出现此错误:

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

and when I change CascadeType to something else I got this error: 当我将CascadeType更改为其他内容时,出现此错误:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.RCSTT.library.FieldMapper

and here is where I save Offer : 这是我保存Offer的地方:

public void insert(Offer offer) throws SQLException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    session.save(offer);
    tx.commit();
    session.close();
}

and I don't use session in somewhere else. 而且我不在其他地方使用会话。

in tx.commit(); tx.commit(); line throws explained exceptions. 行抛出解释了异常。

Thanks for your help. 谢谢你的帮助。

The first exception leads me to believe that this is not a problem with your mapping/entities but with how the object lifecycle or Hibernate session is handled. 第一个例外使我相信这不是您的映射/实体的问题,而是对象生命周期或Hibernate会话的处理方式。

Are the FieldMappers that you're trying to save already persistent (in another session)? 您要保存的FieldMappers是否已经永久保存(在另一个会话中)? You might need to detach those first. 您可能需要先分离它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM