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 inscrutible. 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 inscrutible 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 inscrutible 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.

« Is Apple ruining MacBook Pro or iMac performance with crappy cooling hardware? Counter Measures: Doctor Who and UNIT lacking both The Doctor and UNIT »
2016 Election Acer C720 Ad block AkashaCMS Amazon Amazon Kindle Amiga Android Anti-Fascism Apple Apple Hardware History Apple iPhone Apple iPhone Hardware April 1st Arduino ARM Compilation Astronomy Asynchronous Programming Authoritarianism Automated Social Posting Ayo.JS Bells Law Big Brother Big Finish Black Holes Blade Runner Blogger Blogging Books Botnet Botnets Cassette Tapes Cellphones Christopher Eccleston Chrome Chrome Apps Chromebook Chromebooks Chromebox ChromeOS CIA CitiCards Citizen Journalism Civil Liberties Clinton Cluster Computing Command Line Tools Computer Hardware Computer Repair Computers Cross Compilation Crouton Curiosity Rover Cyber Security Cybermen Daleks Darth Vader Data backup Data Storage Database Database Backup Databases David Tenant DDoS Botnet Detect Adblocker Developers Editors Digital Photography DIY DIY Repair DNP3 Docker Doctor Who Doctor Who Paradox Drobo Drupal Drupal Themes DVD E-Books E-Readers Early Computers Election Hacks Electric Bicycles Electric Vehicles Electron Emdebian Energy Efficiency Enterprise Node EPUB ESP8266 Ethical Curation Eurovision Event Driven Asynchronous Express Facebook Fake News Fedora VirtualBox File transfer without iTunes FireFly Fraud Freedom of Speech Gallifrey git Gitlab GMAIL Google Google Chrome Google Gnome Google+ Government Spying Great Britain Heat Loss Hibernate Home Automation HTTPS I2C Protocol Image Analysis Image Conversion Image Processing ImageMagick InfluxDB Infrared Thermometers Insulation Internet Internet Advertising Internet Law Internet of Things Internet Policy Internet Privacy iOS Devices iPad iPhone iPhone hacking Iron Man Iternet of Things iTunes Java JavaScript JavaScript Injection JDBC John Simms Journalism Joyent Kindle Marketplace Lets Encrypt LibreOffice Linux Linux Hints Linux Single Board Computers Logging Mac OS Mac OS X MacOS X setup Make Money Online MariaDB Mars Matt Lucas MEADS Anti-Missile Mercurial Michele Gomez Micro Apartments Military Hardware Minification Minimized CSS Minimized HTML Minimized JavaScript Missy Mobile Applications MODBUS Mondas MongoDB Mongoose Monty Python MQTT Music Player Music Streaming MySQL NanoPi Nardole NASA Net Neutrality Node Web Development Node.js Node.js Database Node.js Testing Node.JS Web Development Node.x North Korea Online advertising Online Fraud Online Journalism Online Video Open Media Vault Open Source Governance Open Source Licenses Open Source Software OpenAPI OpenVPN Personal Flight Peter Capaldi Photography PHP Plex Plex Media Server Political Protest Postal Service Power Control Privacy Production use Public Violence Raspberry Pi Raspberry Pi 3 Raspberry Pi Zero Recycling Remote Desktop Republicans Retro-Technology Reviews Right to Repair River Song Robotics Rocket Ships RSS News Readers rsync Russia Russia Troll Factory SCADA Scheme Science Fiction Season 1 Season 10 Season 11 Security Security Cameras Server-side JavaScript Shell Scripts Silence Simsimi Skype Social Media Warfare Social Networks Software Development Space Flight Space Ship Reuse Space Ships SpaceX Spear Phishing Spring Spring Boot SQLite3 SSD Drives SSD upgrade SSH SSH Key SSL Swagger Synchronizing Files Telescopes Terrorism The Cybermen The Daleks The Master Time-Series Database Torchwood Total Information Awareness Trump Trump Administration Ubuntu UDOO Virtual Private Networks VirtualBox VLC VNC VOIP Web Applications Web Developer Resources Web Development Web Development Tools Web Marketing Website Advertising Weeping Angels WhatsApp Window Insulation Wordpress YouTube