Hibernate column transformer

2019-08-14 04:44发布

问题:

I am new to Hibernate. I have a use case where I need to apply a transformer (encrypt/encode) on the persistent class member just before it is saved and (decrypt/decode) after the data is loaded. What I am looking at is something like this:

public class PersistentClass {

    @Encrypt(transformer=DoubleTransformer)
    public Double dataToBeEncoded;

    public Double persistAsIs;
}

All my transformers result in text data that will be persisted in db and I want to define transformers once and reuse it in all the persistent classes. Is there an easy way to do this?

回答1:

Yes, there is: JPA life cycle callbacks, or Hibernate inerceptors. Just implement the Pre-Persist, Pre-Update and Post-Load listeners.