JPA: use String fields, but change them and store as byte array

we are using JSON String in our application to store a lot of configuration data. Now we want to store this in the database as a BLOB. The JSON string will be converted to binary representation ( BSON ) and then we want to store that.

Entity:

@Entity
@Table(name="TBL_CONFIG")
public class ConfigEntity {

    [...]

    @Column(name = "CONFIG")
    @JSON
    private String config;

    [...]
}

      

Global EntityListener:

public class JsonBinaryConversionListener {

    @PrePersist
    public void process() {
        // Check @JSON fields and for every field
        [...]
       field.set(objectConversion.toBson(field.get()));
        [...]
        // The field is String, the conversion gives us a byte array
    }

}

      

The CONFIG column is set to BLOB. Only using @Lob annotation doesn't work because we want to change the value manually.

Is there a way we can implement this through JPA?

+3


source to share


1 answer


If you are using EclipseLink you can use a converter,

see, http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_converter.htm#CHDEHJEB

Otherwise, you can use property accessors (get / set) to transform the data,



http://en.wikibooks.org/wiki/Java_Persistence/Basic_Attributes#Conversion

JPA 2.1 project also offered converter support.

+1


source







All Articles