object references an unsaved transient instance -

2019-01-01 01:42发布

I receive following error when I save the object using Hibernate

object references an unsaved transient instance - save the transient instance before flushing

23条回答
其实,你不懂
2楼-- · 2019-01-01 02:09

Simple way of solving this issue is save the both entity. first save the child entity and then save the parent entity. Because parent entity is depend on child entity for the foreign key value.

Below simple exam of one to one relationship

insert into Department (name, numOfemp, Depno) values (?, ?, ?)
Hibernate: insert into Employee (SSN, dep_Depno, firstName, lastName, middleName, empno) values (?, ?, ?, ?, ?, ?)

Session session=sf.openSession();
        session.beginTransaction();
        session.save(dep);
        session.save(emp);
查看更多
谁念西风独自凉
3楼-- · 2019-01-01 02:10

In my case it was caused by not having CascadeType on the @ManyToOne side of the bidirectional relationship. To be more precise, I had CascadeType.ALL on @OneToMany side and did not have it on @ManyToOne. Adding CascadeType.ALL to @ManyToOne resolved the issue. One-to-many side:

@OneToMany(cascade = CascadeType.ALL, mappedBy="globalConfig", orphanRemoval = true)
private Set<GlobalConfigScope>gcScopeSet;

Many-to-one side (caused the problem)

@ManyToOne
@JoinColumn(name="global_config_id")
private GlobalConfig globalConfig;

Many-to-one (fixed by adding CascadeType.PERSIST)

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name="global_config_id")
private GlobalConfig globalConfig;
查看更多
裙下三千臣
4楼-- · 2019-01-01 02:11

beside all other good answers, this could happen if you use merge to persist an object and accidentally forget to use merged reference of the object in the parent class. consider the following example

merge(A);
B.setA(A);
persist(B);

In this case, you merge A but forget to use merged object of A. to solve the problem you must rewrite the code like this.

A=merge(A);//difference is here
B.setA(A);
persist(B);
查看更多
看风景的人
5楼-- · 2019-01-01 02:13

Or, if you want to use minimal "powers" (e.g. if you don't want a cascade delete) to achieve what you want, use

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

...

@Cascade({CascadeType.SAVE_UPDATE})
private Set<Child> children;
查看更多
春风洒进眼中
6楼-- · 2019-01-01 02:15

If you're using Spring Data JPA then addition @Transactional annotation to your service implementation would solve the issue.

查看更多
登录 后发表回答