2

I am trying to save an entity using JPA but getting NotSerializableException for a field of type Optional. Here my goal is to store custom object (here it is of type Grade) in JSON serialized form.

[Student.java]

@Entity
@Table(name = "student")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Size(min = 3, max = 20)
    private String name;

    @Lob
    private Grade grade;

    public Student() {
    }

[Grade.java]

public class Grade implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 7351334541533041431L;
    private Optional<Integer> marks;

    public Optional<Integer> getMarks() {
        return marks;
    }

    public void setMarks(Optional<Integer> marks) {
        this.marks = marks;
    }

    @Override
    public String toString() {
        return "Grade [marks=" + marks + "]";
    }

}

[StudentRepository.java]

public interface StudentRepository extends JpaRepository<Student, Long> {

    public Student findByName(String name);
}

[StudentRepositoryTest.java]

@RunWith(SpringRunner.class)
@DataJpaTest
public class StudentRepositoryTest {
    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private StudentRepository studentRepository;

    @Test
    public void whenFindByName_thenReturnEmployee() {

        // given
        Student alex = new Student("alex");
        Grade grade = new Grade();
        grade.setMarks(Optional.ofNullable(90));
        alex.setGrade(grade);

        entityManager.persist(alex);
        entityManager.flush();

        // when
        Student found = studentRepository.findByName(alex.getName());

        System.out.println(found);
        // then
        assertThat(found.getName()).isEqualTo(alex.getName());
    }
}

After running above test getting following exception for marks field in Grade class:

Caused by: java.io.NotSerializableException: java.util.Optional
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.hibernate.internal.util.SerializationHelper.serialize(SerializationHelper.java:115)
    ... 49 more

I have included following dependency to support java8 data types for Jackson:

<dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jdk8</artifactId>
        </dependency>

Spring boot version: 2.1.6.RELEASE

Shared the same code at: https://github.com/Omkar-Shetkar/spring-repo-test

What could be missing here?

0

4 Answers 4

3

It looks like Hibernate tries to serialize your Grade object and since it uses the default serialization algorithm, it tries to serialize the Optional<Integer> marks field.

Now, in Java Optional is not serializable: See https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

So the serialization fails.

Since Optional is not intended to be used in data fields (see [this discussion] for reasons1), consider removing an optional, leaving Integer marks)

2
  • Actually my goal is to store custom object in an entity in JSON serialized form into the table. A custom object contains other fields apart from Optional also. It seems hibernate is using Java serialization to store the object. Can I use jackson provided JSON serialization instead ? Aug 26, 2019 at 6:06
  • I'm not really familiar with Hibernate/JPA, but this seems to be relevant: stackoverflow.com/questions/25738569/… Aug 26, 2019 at 6:11
1

Yes, Optional is not Serializable. JPA attempts to serialize non-text (anything but String, char[] or Char[]) fields marked with @Lob.

The recommended approach would be using a JPA converter to serialize the object into a Json while persisting and deserialize the persisted Json on reads. Jackson supports serializing Optional fields, you just have to add jackson-datatype-jdk8 dependency and register Jdk8Module on your ObjectMapper. A GradeConverter implementation looks like this:

@Converter
public class GradeConverter implements AttributeConverter<Grade, String> {

    private ObjectMapper objectMapper;

    public GradeConverter() {
        objectMapper = new ObjectMapper();
        objectMapper.registerModule(new Jdk8Module());
    }

    @Override
    public String convertToDatabaseColumn(Grade grade) {

        if (grade == null) {
            return null;
        }

        return objectMapper.writeValueAsString(grade);
    }

    @Override
    public Grade convertToEntityAttribute(String s) {

        if (s == null) {
            return null;
        }

        return objectMapper.readValue(s, Grade.class);
    }
}

And on your Grade field:

@Convert(converter = GradeConverter.class)
private Grade grade;

If you insist on serializing the field (I mean Java serialization), you should provide custom serialization methods. You could read more about that here.

1

Jackson is completely irrelevant here; when you're saying that you want to use Serializable, you're talking about Java serialization, and for whatever reason Optional isn't Serializable.

The recommended approach for "optional" properties like this in persistent entities is to store the actual value as a nullable field and translate in the getter and setter.

1

The com.google.common.base also have the Optional class which is serializable:

Java Doc

Maven Repo

2

Not the answer you're looking for? Browse other questions tagged or ask your own question.