A fix for org hibernate TransientPropertyValueException in Spring Boot

By: (plus.google.com) +David Herron; Date: September 1, 2017

Tags: Spring Boot

Error messages coming out of Spring can be more than inscrutable. In this case I'm defining a REST API using Swagger/OpenAPI targeting a Spring Boot implementation. The object models are complex, with lots of nested objects. It turns out you can POST a big blob of JSON with all kinds of structure, and Spring/JPA/Hibernate will swallow the whole thing and automatically parcel everything out to the corresponding database table. If you define the JPA annotations correctly, that is.

Get an annotation incorrect, and you'll be left scratching your head over what the heck you're being told by the error message. The Spring Team promises on a huge stack of bibles that Spring Boot automatically takes care of zillions of things for you, and it's so easy to write your code. In my experience it's instead a matter of papering complexity over complexity over a system containing about a thousand kitchen sinks worth of excess capabilities. There's no amount of papering-over that kind of complexity that will make the system simpler. But, the boss-man says to use Spring Boot, so here goes.

Let's start with the error:

2017-09-01 22:47:43.187 ERROR 5 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.amzur.orangebuttonapi.model.SystemPerformance.estimated -> com.amzur.orangebuttonapi.model.Estimated; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.amzur.orangebuttonapi.model.SystemPerformance.estimated -> com.amzur.orangebuttonapi.model.Estimated] with root cause

org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.amzur.orangebuttonapi.model.SystemPerformance.estimated -> com.amzur.orangebuttonapi.model.Estimated
  at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:379) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:126) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:425) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.event.internal.DefaultPersistEventListener.justCascade(DefaultPersistEventListener.java:171) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.event.internal.DefaultPersistEventListener.entityIsPersistent(DefaultPersistEventListener.java:164) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.internal.SessionImpl.firePersistOnFlush(SessionImpl.java:802) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.internal.SessionImpl.persistOnFlush(SessionImpl.java:795) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.engine.spi.CascadingActions$8.cascade(CascadingActions.java:340) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:398) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:162) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:111) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:150) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:141) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:74) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]
  at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:38) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]

This stack trace actually goes on for a couple more screen-fulls. That's a sign right there of too much complexity.

Accompanying this was another inscrutable error message (this stack trace also goes for a couple screens):

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "undefined"
  at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:128) ~[spring-web-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
  at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
  at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158) [spring-web-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
  at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128) [spring-web-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]

In this case the error message is useful enough to go directly to the problem. I've seen other instances like what we'll discuss shortly with a completely inscrutable error message which left me grasping at straws.

The object model includes a SystemPerformance class with an estimated field referring to the Modelled class. If you read the error closely, you'll see this relationship mentioned.

This does NOT, however, explain what TransientPropertyValueException means, nor what is a transient property. The error message helpfully tells us "object references an unsaved transient instance" and that we should save the transient whatever instance thingy. Whatever. Where do we learn what that means?

(docs.jboss.org) Section 5 of the Hibernate User Guide has this helpful explanation:

Persistent data has a state in relation to both a persistence context and the underlying database.

transient the entity has just been instantiated and is not associated with a persistence context. It has no persistent representation in the database and typically no identifier value has been assigned (unless the assigned generator was used).

managed, or persistent the entity has an associated identifier and is associated with a persistence context. It may or may not physically exist in the database yet.

detached the entity has an associated identifier, but is no longer associated with a persistence context (usually because the persistence context was closed or the instance was evicted from the context)

removed the entity has an associated identifier and is associated with a persistence context, however it is scheduled for removal from the database.

This begins to explain the situation. A transient object hasn't been saved -- the phrase "with a persistent context" is probably a bit of vague gobbledygook meaning "database".

Now we can look at a bit of code:

@Entity
public class SystemPerformance   {

    @Id @GeneratedValue
    @JsonProperty("systemPerformanceID")
    private Integer systemPerformanceID;

    // ... other fields

    @JsonProperty("estimated")
    @ManyToOne
    private Estimated estimated = null;

    // ... other fields
}

The Estimated object:

@Entity
public class Estimated   {

    @Id @GeneratedValue
    @JsonProperty("estimatedID")
    private Integer estimatedID;

    // ... other fields
}

The problem here is the nature of the relationship as expressed by the Annotations. It's just flatly wrong. First, we do not have a ManyToOne relationship, but a OneToOne. Second, we've not specified any cascade action nor the column name on which to join to the other table.

That is, because both these have the @Entity annotation, each gets a generated database table created by Hibernate. When Hibernate generates the SQL code it needs to instantiate the Estimated object using a SELECT statement on that table. The SystemPerformance table needs a column to hold the value of the ID of the corresponding row in the Estimated table.

In theory Hibernate simplifies our life by automatically setting up those tables and managing the relationships for us. But we have to cooperate with Hibernate by ensuring we've declared the relationship correctly. We failed to do so above.

@Entity
public class SystemPerformance   {

    @Id @GeneratedValue
    @JsonProperty("systemPerformanceID")
    private Integer systemPerformanceID;

    // ... other fields

    @JsonProperty("estimated")
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="estimatedID")
    private Estimated estimated = null;

    // ... other fields
}

Instead, this is how the annotations should have gone. It declares a OneToOne relationship. The CascadeType.ALL means that all operations on SystemPerformance entries pass through to the corresponding row in the Estimated table. Rows in that table are identified by the estimatedID column.