Faizan Ali
Faizan Ali

Reputation: 97

Serializing List to JSON Array

I have a JPA entity with a List of custom objects as one of its fields. Using a Jackson converter, I've managed to persist this list as a JSON array into a MySQL database, but Iam unable to insert into this list after its initial creation.

I can successfully retrieve the existing list, add a new object in memory(and test that it has been inserted), then save it via a Spring REST repository. However, it never seems to persist. Any ideas? Here is my code (this is a Spring Boot project FYI):

Candidate entity with a List inside

@Entity
@Table(name = "Candidates", schema = "Candidate")
public class Candidate extends ResourceSupport {

@Id
@Column(name = "CandidateID")
private Long candidateID;

// More fields

@Column(name = "Fields")
@Convert(converter = CollectionConverter.class)
private List<CandidateField> fields;

//Getters & setters
}

CandidateField class which makes up the List above. The CandidateField is simply a POJO that models the JSON stored in a single field in the Candidate table, it is not an independent entity.

public class CandidateField {

private Long fieldID;
private String name;
private boolean current;

public CandidateField () {

}

public CandidateField (Long fieldID, String name, boolean current) {
    this.fieldID = fieldID;
    this.name = name;
    this.current = current;
}

//Getters & Setters
}

Converter

public class CollectionConverter implements AttributeConverter<List<CandidateField>, String> {

private ObjectMapper objectMapper = new ObjectMapper();

@Override
public String convertToDatabaseColumn(List<CandidateField> object) {
    try {
        return objectMapper.writeValueAsString(object);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return "";
    }
}

@Override
public List<CandidateField> convertToEntityAttribute(String data) {
    try {
        return objectMapper.readValue(data, new TypeReference<List<CandidateField>>() {});
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

Code that persists to database

public void addField(Long fieldID, Long candidateID) {
    Candidate candidate = repository.findOne(candidateID);
    candidate.getFields().add(new CandidateField(fieldID, "", true));
    repository.saveAndFlush(candidate);
}

Repository

@RepositoryRestResource
public interface CandidateRepository extends JpaRepository<Candidate,Long>{}

I can't seem to figure out why this won't persist. Any help will be very much appreciated. Cheers!

Upvotes: 4

Views: 2975

Answers (1)

Brian
Brian

Reputation: 902

Consider defining the cascade type for your collection.

When you persist your Candidate objects the operation is not cascaded by default and thus you need to define it yourself unless you persist your CandidateField objects directly.

Upvotes: 1

Related Questions