Insert followed by Update call with JSON column type when using Spring Data JPA

1.2k views Asked by At

I'm using non-springboot app running on Tomcat (due to legacy reason) with spring data JPA.

My MySQL database has students field of type JSON which stores list of students:

Student.java

@JsonProperty("students"")
@NotNull(message = "Null required field: students")
@Valid
@Convert(converter = MyConverter.class)
private List<StudentNode> students;

MyConverter.java

    @Converter
        public class MyConverter extends MyBaseConverter<Object> {
    }

MyBaseConverter.java

public abstract class MyBaseConverter<T> implements AttributeConverter<List<T>, String> {
private static final ObjectMapper mapper;

static {
    mapper = new ObjectMapper();
}

@Override
public String convertToDatabaseColumn(List<T> attribute) {
    if (attribute == null || attribute.isEmpty()) {
        return null;
    }

    try {
        return mapper.writeValueAsString(attribute);
    } catch (JsonProcessingException e) {
        return null;
    }
}

@Override
public List<T> convertToEntityAttribute(String dbData) {
    try {
        if (StringUtils.isBlank(dbData)) {
            return null;
        }

        return mapper.readValue(dbData, new TypeReference<List<T>>() {});
    } catch (IOException e) {
        return null;
    }
}
}

StudentNode class contains student id and name.

StudentRepository.java uses standard JPA repository as shown below:

@Repository
    public interface StudentRepository extends PagingAndSortingRepository<Student, String> {
}

I'm saving this student data by calling

studentRepository.save(student);

It saves the student record but then it also invokes update query on student unnecessarily. There is no foreign key or any constraint anywhere. Upon debugging with DynamicUpdate, I found that updates are occuring due to JSON field students containing id and name. But I'm not sure how or why JPA is doing like that.

I tried adding equals and hashcode in StudentNode as well as Student.java but no luck.

Anyone has encountered this extra update for JSON column types when using JPA? How to avoid this extra update call?

0

There are 0 answers