JPA/Eclipselink, don’t forget to annotate complex fields with @Mutable

Note to self: Don’t forget to annotate complex fiels with the @Mutable annotation.

 

It might sound noobish, but i’ve just spend the last 2 hours trying to find out why my jpa/eclilpse link entity wasn ‘t updating my ‘complex’ (hashmap) field. At first, i figured it had something to do with the @Converter i was using to serialize/deserialize the HashMap into a JSON string. But eventually it turned out, that the change-tracking mechanism only works for non-mutable/basic fields. And thus, no updates were detected, as i was updating the hashmap, instead of replacing it.

So as it turns out (i should have read the manual ;)) the @Mutable annotation is there to use.

@Entity
public class BasicEntity {

	@Id
	@GeneratedValue
	private int id;
	
	@JsonAdapter(BasicEntityTypeAdapter.class)
	private BasicEntityType type;

	private String location;
	
	private float x;
	private float y;
	
	
	@Convert(converter = JPAHashmapToStringConverter.class) /*store as String/json*/
	@Column(length=4096)
	@Mutable
	private HashMap<String, Object> properties;
}

@Converter
public class JPAHashmapToStringConverter implements AttributeConverter<HashMap<String, Object>,String>{

	  private final static Gson gson = new Gson();
	  private final static Class hashMapClass = new HashMap<String,Object> ().getClass();

	  @Override
	  public String convertToDatabaseColumn(HashMap<String, Object> meta) {
		  if (meta==null)meta = new HashMap<String,Object>();
	      return gson.toJson(meta);
	  }

	  @Override
	  public HashMap<String, Object> convertToEntityAttribute(String dbData) {
		 
		  return gson.fromJson(dbData,hashMapClass);
	  }

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *