Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA not updating column with Converter class

Tags:

java

mysql

jpa

I'm using a Converter class to store a complex class as JSON text in mySQL. When I add a new entity, the Converter class works as intended. However, when I update the entity, the data in the complex class is not updated in the database but it's updated in memory. Other attributes such as Lat and Long are updated. The breakpoint I placed at the convertToDatabaseColumn method and it did not trigger on update.

Object Class

public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String city;
    private String state;
    private String country;
    @Enumerated(EnumType.STRING)
    private StatusType status;
    private String street;
    private double latitude;
    private double longitude;
    @Convert(converter=ProjectPropertyConverter.class)
    private ProjectProperty property;
}

public class ProjectProperty {

    private String description;
    private List<String> projectImgs;
    private Boolean hasImages;
}

Property Converter Class

@Converter (autoApply=true)
public class ProjectPropertyConverter implements AttributeConverter<ProjectProperty, String> {

    @Override
    public String convertToDatabaseColumn(ProjectProperty prop) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(prop);
            return jsonString;
        } catch (Exception e) {
            System.out.print(e.toString());
            return null;
        }

    }

    @Override
    public ProjectProperty convertToEntityAttribute(String jsonValue) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            ProjectProperty p = mapper.readValue(jsonValue, ProjectProperty.class);

            if(p.getProjectImgs().isEmpty())
            {
                p.setHasImages(Boolean.FALSE);
            }
            else
            {
                p.setHasImages(Boolean.TRUE);
            }          
            return p;
        } catch (Exception e) {
            System.out.print(e.toString());
            return null;
        }
    }
}

Method to Update Database

public void modifyEntity(Object entity, String query, HashMap params) {
    try {
        tx.begin();
        em.flush();
        tx.commit();

    } catch (Exception e) {
        e.toString();
    }
}
like image 288
MooCow Avatar asked Oct 15 '25 20:10

MooCow


1 Answers

I came here looking for same answers. Turns out the problem is JPA doesn't know that your object is dirty. This was solved by implementing equals()/hashcode() methods on this complex objects. In your example, implement equals and hashcode for ProjectProperty

Once that is done, JPA is able to identify via these methods that the underlying object is dirty and converts and persists.

like image 67
user5165093 Avatar answered Oct 17 '25 11:10

user5165093