Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: persistent data synchronization, advice needed

Tags:

java

jpa

I'm trying to create JPA class implementing simple interface:

public interface Task<T> {
    public void setData(T data);
    public T getData();
    public void run();
}

For some reasons I need T data to be stored in a serialized form, so my JPA class needs both JPA getters/setters and interface implementation. Obviously, they need to be synchronized somehow.

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class AbstractTask<T extends Serializable> implements Task<T> {
    private T data;
    private byte[] serializedData; // do I need both vars? which one to choose?

    @Override
    @Transient
    public T getData() {
        return data; // or deserialized 'serializedData'?
    }

    @Override
    public void setData(T data) {
        this.data = data; // or serialize into 'serializedData'?
    }

    @Column
    @Lob
    public byte[] getSerializedData() {
        return serializedData; // or serialized 'data'?
    }

    public void setSerializedData(byte[] bytes) {
        this.serializedData = bytes;
        // deserialize 'bytes' into 'data'?
    }
}

What is the correct approach for synchronizing these class variables or how to rebuild one from another? The question is a bit wider than serialization/deserialization and applies to any situation where some object could be uniquely rebuild from JPA persistent data and vice versa.

like image 933
andbi Avatar asked Dec 14 '25 14:12

andbi


1 Answers

The lifecycle callbacks can help you out here. PrePersist and PostLoad in particular.

like image 193
Peter Avatar answered Dec 18 '25 01:12

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!