Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to implement a JPA AttributeConverter for handling NULL properly?

I have written a JPA attribute converter to convert values between java.lang.String and java.nio.Path.

The converter works fine for non-null value. In case of converting null from the Java world to SQL, Hibernate inserts the string value null into the database row. But I would to have (SQL) NULL, so that the column is either empty or in case of NOT NULL contraint a constraint violation will be caused.

What do I wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The converter looks like this:

@Converter
public class PathConverter 
  implements AttributeConverter<Path, String> {
  @Override
  public String convertToDatabaseColumn(Path path) {
    return Objects.toString(path);
  }

  @Override
  public Path convertToEntityAttribute(String columnValue) {
    return Optional.ofNullable(columnValue)
                   .map(Paths::get).orElse(null);
  }
}

I am using Spring Boot 2.7.1 with Hibernate for my application.

>Solution :

Change:

public String convertToDatabaseColumn(Path path) {
   return Objects.toString(path);
}

To:

 public String convertToDatabaseColumn(Path path) {
    return path == null ? null : Objects.toString(path);
  }

because Objects.toString() return the string "null" if the value is null

From the documentation:

Returns the result of calling toString for a non-null argument and "null" for a null argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading