@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
}
以下程序不起作用->
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();
如果我将 Section.java 中的级联选项更改为 CascadeType.ALL 那么它可以工作。
@OneToOne(optional = false,cascade = CascadeType.PERSIST) --- > CascadeType.ALL
@JoinColumn(name = "Exch_ID")
private Exchange exchange;
我认为 PERSIST 应该保存我的对象 d=,但它会引发异常:
org.hibernate.TransientPropertyValueException:非空属性引用瞬态值 - 瞬态实例必须在当前操作之前保存:Section.exchange -> Exchange