The One Hibernate Mistake We Have All Done and Three Ways of Fixing It

Emanuel Trandafir
Javarevisited
Published in
4 min readAug 25, 2022

--

Image By Telegraph — How to Hibernate like a pro

In this article, we’ll discuss a faulty and misleading usage of Hibernate’s @Column(nullable = false).

1. The Happy Flow

For the code examples in this article, we’ll use the Student entity model:

The firstName field should be always present for a valid Student entity. So, we’ll use the nullable = false attribute of the @Column annotation to ensure we don’t insert null values into the database.

Let’s try to save a Student entity without setting the firstName attribute:

studentRepository.save(new Student());

If we will do this, we would expect the validation to fail and throw an exemption, which is, in fact, happening:

org.springframework.dao.DataIntegrityViolationException: 
not-null property references a null or transient value

--

--

Emanuel Trandafir
Javarevisited

Hi, I'm Emanuel Trandafir, a Java developer from Romania. I have a strong passion for clean code, software design, and unit testing.