1. Overview

In this tutorial, we’ll see how to solve a common Hibernate error – “org.hibernate.TransientObjectException: object references an unsaved transient instance”. We get this error from the Hibernate session when we try to persist a managed entity, and that entity references an unsaved transient instance.

2. Describing the Problem

The TransientObjectException is “Thrown when the user passes a transient instance to a session method that expects a persistent instance”.

Now, the most straightforward solution to avoid this exception would be to get a persisted instance of the required entity by either persisting a new instance or fetching one from the database and associate it in the dependant instance before persisting it. However, doing so only covers this particular scenario and doesn’t cater to other use cases.

To cover all scenarios, we need a solution to cascade our save/update/delete operations for entity relationships that depend on the existence of another entity. We can achieve that by using a proper CascadeType in the entity associations.

In the following sections, we’ll create some Hibernate entities and their associations. Then, we’ll try to persist those entities and see why the session throws an exception. Finally, we’ll solve those exceptions by using proper CascadeType(s).

3. @OneToOne Association

In this section, we’ll see how to solve the TransientObjectException in @OneToOne associations.

3.1. Entities

First, let’s create a User entity:

@Entity
@Table(name = "user")
public class User {

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

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @OneToOne
    @JoinColumn(name = "address_id", referencedColumnName = "id")
    private Address address;

    // standard getters and setters
}

And let’s create the associated Address entity:

@Entity
@Table(name = "address")
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "city")
    private String city;

    @Column(name = "street")
    private String street;

    @OneToOne(mappedBy = "address")
    private User user;

    // standard getters and setters
}

3.2. Producing the Error

Next, we’ll add a unit test to save a User in the database:

@Test
public void whenSaveEntitiesWithOneToOneAssociation_thenSuccess() {
    User user = new User("Bob", "Smith");
    Address address = new Address("London", "221b Baker Street");
    user.setAddress(address);
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();
    session.close();
}

Now, when we run the above test, we get an exception:

java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.baeldung.hibernate.exception.transientobject.entity.Address

Here, in this example, we associated a new/transient Address instance with a new/transient User instance. Then, we got the TransientObjectException when we tried to persist the User instance because the Hibernate session is expecting the Address entity to be a persistent instance. In other words, the Address should have already been saved/available in the database when persisting the User.

3.3. Solving the Error

Finally, let’s update the User entity and use a proper CascadeType for the User-Address association:

@Entity
@Table(name = "user")
public class User {
    ...
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "address_id", referencedColumnName = "id")
    private Address address;
    ...
}

Now, whenever we save/delete a User, the Hibernate session will save/delete the associated Address as well, and the session will not throw the TransientObjectException.

4. @OneToMany and @ManyToOne Associations

In this section, we’ll see how to solve the TransientObjectException in @OneToMany and @ManyToOne associations.

4.1. Entities

First, let’s create an Employee entity:

@Entity
@Table(name = "employee")
public class Employee {

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

    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    // standard getters and setters
}

And the associated Department entity:

@Entity
@Table(name = "department")
public class Department {

    @Id
    @Column(name = "id")
    private String id;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "department")
    private Set<Employee> employees = new HashSet<>();

    public void addEmployee(Employee employee) {
        employees.add(employee);
    }

    // standard getters and setters
}

4.2. Producing the Error

Next, we’ll add a unit test to persist an Employee in the database:

@Test
public void whenPersistEntitiesWithOneToManyAssociation_thenSuccess() {
    Department department = new Department();
    department.setName("IT Support");
    Employee employee = new Employee("John Doe");
    employee.setDepartment(department);
    
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.persist(employee);
    session.getTransaction().commit();
    session.close();
}

Now, when we run the above test, we get an exception:

java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.baeldung.hibernate.exception.transientobject.entity.Department

Here, in this example, we associated a new/transient Employee instance with a new/transient Department instance. Then, we got the TransientObjectException when we tried to persist the Employee instance because the Hibernate session is expecting the Department entity to be a persistent instance. In other words, the Department should have already been saved/available in the database when persisting the Employee.

4.3. Solving the Error

Finally, let’s update the Employee entity and use a proper CascadeType for the Employee-Department association:

@Entity
@Table(name = "employee")
public class Employee {
    ...
    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    @JoinColumn(name = "department_id")
    private Department department;
    ...
}

And let’s update the Department entity to use a proper CascadeType for the Department-Employees association:

@Entity
@Table(name = "department")
public class Department {
    ...
    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Employee> employees = new HashSet<>();
    ...
}

Now, by using @Cascade(CascadeType.SAVE_UPDATE) on the Employee-Department association, whenever we associate a new Department instance with a new Employee instance and save the Employee, the Hibernate session will save the associated Department instance as well.

Similarly, by using cascade = CascadeType.ALL on the Department-Employees association, the Hibernate session will cascade all operations from a Department to the associated Employee(s). For example, removing a Department will remove all Employee(s) associated with that Department.

5. @ManyToMany Association

In this section, we’ll see how to solve the TransientObjectException in @ManyToMany associations.

5.1. Entities

Let’s create a Book entity:

@Entity
@Table(name = "book")
public class Book {

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

    @Column(name = "title")
    private String title;

    @ManyToMany
    @JoinColumn(name = "author_id")
    private Set<Author> authors = new HashSet<>();

    public void addAuthor(Author author) {
        authors.add(author);
    }

    // standard getters and setters
}

And let’s create the associated Author entity:

@Entity
@Table(name = "author")
public class Author {

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

    @Column(name = "name")
    private String name;

    @ManyToMany
    @JoinColumn(name = "book_id")
    private Set<Book> books = new HashSet<>();

    public void addBook(Book book) {
        books.add(book);
    }

    // standard getters and setters
}

5.2. Producing the Problem

Next, let’s add some unit tests to save a Book with multiple authors, and an Author with multiple books in the database, respectively:

@Test
public void whenSaveEntitiesWithManyToManyAssociation_thenSuccess_1() {
    Book book = new Book("Design Patterns: Elements of Reusable Object-Oriented Software");
    book.addAuthor(new Author("Erich Gamma"));
    book.addAuthor(new Author("John Vlissides"));
    book.addAuthor(new Author("Richard Helm"));
    book.addAuthor(new Author("Ralph Johnson"));
    
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(book);
    session.getTransaction().commit();
    session.close();
}

@Test
public void whenSaveEntitiesWithManyToManyAssociation_thenSuccess_2() {
    Author author = new Author("Erich Gamma");
    author.addBook(new Book("Design Patterns: Elements of Reusable Object-Oriented Software"));
    author.addBook(new Book("Introduction to Object Orient Design in C"));
    
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(author);
    session.getTransaction().commit();
    session.close();
}

Now, when we run the above tests, we get the following exceptions, respectively:

java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.baeldung.hibernate.exception.transientobject.entity.Author

java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.baeldung.hibernate.exception.transientobject.entity.Book

Similarly, in these examples, we got TransientObjectException when we associated new/transient instances with an instance and tried to persist that instance.

5.3. Solving the Problem

Finally, let’s update the Author entity and use proper CascadeTypes for the Authors-Books association:

@Entity
@Table(name = "author")
public class Author {
    ...
    @ManyToMany
    @Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.PERSIST})
    @JoinColumn(name = "book_id")
    private Set<Book> books = new HashSet<>();
    ...
}

Similarly, let’s update the Book entity and use proper CascadeTypes for the Books-Authors association:

@Entity
@Table(name = "book")
public class Book {
    ...
    @ManyToMany
    @Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.PERSIST})
    @JoinColumn(name = "author_id")
    private Set<Author> authors = new HashSet<>();
    ...
}

Note that we cannot use the CascadeType.ALL in a @ManyToMany association because we don’t want to delete the Book if an Author is deleted and vice versa.

6. Conclusion

To sum up, this article shows how defining a proper CascadeType can solve the “org.hibernate.TransientObjectException: object references an unsaved transient instance” error.

As always, you can find the code for this example over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are closed on this article!