Search code examples
springhibernatejpaone-to-onehibernate-annotations

Hibernate with OneToOne relationship - Persist only the parent Entity


I am new to Hibernate and I have been struggling to persist a parent entity without persisting a child entity (because it is already persisted and has been previously loaded).

I tried to find some help on many different internet sites but got no luck to get one that clearly relates to my issue. Hope you guys can help.

Imagine the following scenario:

I have an entity (TableA) that references another entity (TableB).

@Entity
@Table(name = "A")
public class TableA implements Serializable{
     private static final long serialVersionUID = 1L;

     @Id
     @Column(name="idtablea")
     @GeneratedValue(strategy=GenerationType.AUTO)
     private int id;

     @GeneratedValue(generator="IdBGenerator")
     @GenericGenerator(name="IdBGenerator", strategy="foreign", 
            parameters=@Parameter(value="tableB", name="property"))
     private int idb;
     @OneToOne
     @JoinColumn(name = "idtableb", insertable = false, updatable = false)
     private TableB tableB;

     //other properties

     //constructors

     //getters and setters
}

and TableB entity is defined as follows:

@Entity
@Table(name = "B")
public class TableB implements Serializable{
     private static final long serialVersionUID = 1L;

     @Id
     @Column(name = "idtableb")
     @GeneratedValue(strategy=GenerationType.AUTO)
     private int id;

     //other properties

     //constructors

     //getters and setters
}

I construct an instance of TableA with a reference of an instance of TableB.

Now I want to persist TableA to database (table A) and link it to table B without persisting TableB (because it was persisted in a previous transaction). For this I am using the following code:

Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(TableA);
tx.commit();
session.close();

Everytime the above code is executed the following exception is thrown when trying to commit the transaction:

Severe: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.mypackage.TableB

Can you kindly help me understand the issue here? Thanks in advance.

I am using Java 8, Hibernate 3.6.8 and Spring 4.1.5.


Solution

  • I construct an instance of TableA with a reference of an instance of TableB.

    Where are you getting this instance of TableB from ? You have to load it from database where it got persisted in another transaction using Hibernate API (use get or preferably load as you only want to set relation) and then setting it into entity from Table A. Looks like you are creating a new object which is transient and then setting it into entity from TableA. Since the relation graph contains a transient entity therefore you are getting this error.