Hibernate:CascadeType.PERSIST不起作用,但CascadeType.ALL保存对象

Hak*_*ata 7 hibernate cascade

@Entity
@Table(name = "Section_INST")
public class Section {

@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "Section_ID_GENERATOR")
@SequenceGenerator(name = "Section_ID_GENERATOR",sequenceName = "Section_ID_SEQUENCER" , initialValue = 1 , allocationSize = 1)
@Column(name = "Section_ID")
private int Id;

@Column(name = "Section_Name")
private String name;

@OneToOne(optional = false,cascade = CascadeType.PERSIST)
@JoinColumn(name = "Exch_ID")
private Exchange exchange;

//---Constructor and Getter Setters-----
}


@Entity
@Table(name = "EXCHANGE_INST")
public class Exchange {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "Exchange_ID_GENERATOR")
@SequenceGenerator(name = "Exchange_ID_GENERATOR",sequenceName = "Exchange_ID_SEQUENCER" , initialValue = 1 , allocationSize = 1)
@Column(name = "Exchange_ID")
private int Id;

@Column(name = "Exchange_name")
private String name;

@OneToOne(mappedBy ="exchange")
private Section section;

//-----------Getter and Setter...And Constructor
Run Code Online (Sandbox Code Playgroud)

}

以下程序不起作用 - >

    final SessionFactory sessionFactory = configuration.buildSessionFactory();
    final Session session = sessionFactory.openSession();
    session.beginTransaction();

    final Exchange exchange = new Exchange("MyExchange");
    final Section section = new Section("MySection" , exchange);
    exchange.setSection(section);
    session.save(section);

    session.getTransaction().commit();
    session.close();
Run Code Online (Sandbox Code Playgroud)

如果我将Section.java中的级联选项更改为CascadeType.ALL,那么它可以工作.

@OneToOne(optional = false,cascade = CascadeType.PERSIST)   --- > CascadeType.ALL 
@JoinColumn(name = "Exch_ID")
private Exchange exchange;
Run Code Online (Sandbox Code Playgroud)

我认为PERSIST应该保存我的对象d =,但它抛出异常:

org.hibernate.TransientPropertyValueException:非null属性引用瞬态值 - 必须在当前操作之前保存瞬态实例:Section.exchange - > Exchange

JB *_*zet 17

对于save()要级联的操作,您需要CascadeType.SAVE_UPDATE使用专有的Hibernate Cascade注释启用,因为save()不是标准的JPA操作.或者您需要使用persist()方法,而不是save()方法.

  • 我已经失去了几个小时的生命,因此我永远不会回来,谢谢!这并不明显且记录不完整.更多信息:https://forum.hibernate.org/viewtopic.php?t = 951275 (6认同)
  • 我失去了这么多个小时...因为......那个ORM文件... =( (3认同)