小编典典

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

hibernate

@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:非null属性引用一个瞬态值-
必须在当前操作之前保存瞬态实例:Section.exchange-> Exchange


阅读 677

收藏
2020-06-20

共1个答案

小编典典

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

2020-06-20