Channa Channa - 3 months ago 4
Java Question

How to configure attribute of Hibernate @Type annotation

In my application, I have enable the jasypt encryption with @Type annotation. But when I need to deploy the application without any encryption then I have to change the attribute of the @Type annotation as following manner. Currently I'm proceed this operation manually. Is there any way to make this configurable (according to configuration value pickup the attribute of the @Type annotation)? Thanks.

@Entity
@Table
public class Data {

@Id
private Integer id;

@Type(type = "encryptedString") // Need to enable for Encryption
@Type(type = "org.hibernate.type.TextType") // Need to enable for Non Encryption
private String data;
}

Answer

With the use of “JPA entity life-cycle call back methods” I have handle the Encryption and Decryption as a configurable parameter. Now Hibernate is not responsible for Encryption and Decryption, application related DTOs are itself explicitly proceed the Encryption and Decryption related operations.

@Entity
@Table 
public class Data {

  @Id
  private Integer id;

  @Type(type = "org.hibernate.type.TextType")
  private String data;

  // Before Persist or Update to Database
  @PrePersist
  @PreUpdate
  void beforePersistOrUpdate () {

      // Do encrypt
      if(ProjectProperty.isEncryptionEnabled) {
          this.data = ServiceUtil.commonService.doEncryptString(this.data);
      } 
  }

  // Before Load from Database
  @PostLoad
  void beforeLoad() {

      // Do Decrypt
      if(ProjectProperty.isEncryptionEnabled) {
          this.data = ServiceUtil.commonService.doDecryptString(this.data);
      }
  }
}