Constraint name missing when using Hibernate SQLServer Dialect

Faiz Chachiya
3 min readMar 30, 2022

Have you encountered a missing constraint name in your application error messages, when migrating your application from Oracle to Azure SQL?

Photo by Wolfgang Hasselmann on Unsplash

Hibernate is Java based framework which is quite popular as it simplifies the overall development to perform different kind of operations on the database.

So if you have an application which uses Hibernate where the backend is Azure SQL and if you ever encounter constraint-related errors then the constraint name just shows ‘null’. The constraint exception is of org.hibernate.exception.ConstraintViolationException class type which basically has “getConstraintName()” method that returns ‘null’ instead of the constraint name. Below is the definition of the method from the official documentation.

The actual exception message using “ConstraintException. getCause().getMessage()” showed the constraint name, but then explicitly retrieving the constraint name using “getConstraintName()” returned ‘null’, which you can see in the following screenshot.

After some analysis found that the Hibernate code extracting the constraint name from the exception was returning ‘null’.

The below matrix shows the class hierarchies for both Oracle and Azure SQL dialects, and excerpt from the Hibernate source code that proved that the issue existed within the Hibernate library

If you notice, the Oracle dialect basically has logic in place to extract the constrain name whereas for Azure SQL it results to default behavior.

Solution

Given the limitations within the Hibernate library, the constraint name in the actual error message can be easily extracted by writing a regular expression. For example, if the error message was “Violation of UNIQUE KEY constraint ‘UC_Person2’”, the constraint name could be easily extracted using Regex expression ‘(.*?)’. See the following screenshot for reference.

Note: The issue persists for even latest versions of Hibernate library, the source code for Hibernate dialect is available here for reference.

Hope this helps you if you ever encounter similar like problem when working with Hibernate and Azure SQL database.

(The opinions expressed here represent my own and not those of my current or any previous employers.)

--

--

Faiz Chachiya

Faiz Chachiya is Software Architect, Coder, Technophile, Newbie Writer and loves learning languages. Currently working at Microsoft as Cloud Solution Architect.