Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

cascade - Hibernate : CascadeType.PERSIST does not work but CascadeType.ALL to save object

@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

}

The following program does not work ->

    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();

If i change cascade options in Section.java to CascadeType.ALL then it works.

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

I think PERSIST should save my object d=, but it throws exception :

org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation: Section.exchange -> Exchange

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the save() operation to be cascaded, you need to enable CascadeType.SAVE_UPDATE, using the proprietary Hibernate Cascade annotation, since save() is not a standard JPA operation. Or you need to use the persist() method, and not the save() method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...