Search code examples
javahibernate-mappingclob

how to store java bean object as a clob in DB column(using Hibernate)


My Java bean looks like below public class AuditRptDTO {

private Date timestamp;
private String userId;
private String stName;
private String userType;
private String code;
private Clob oldRecord;
private Clob newRecord;
private String serverIp;

} here in place of oldRecord and newRecord i need to save another bean object. how can i achieve this in hibernate using an XML mapping.


Solution

  • A Simple approach is:

    serialize your Object:

    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
    ObjectOutput out  = new ObjectOutputStream(bos) ;
    out.writeObject(object);
    out.close();
    
    byte[] dataArray = bos.toByteArray();
    

    Base 64 encode the data to get a String.

    String dataString = Base64.encodeBase64String(dataArray);
    

    Then all that s needed is to convert the String to an instance of the Clob interface, you could create your own or use an existing one.

    Clob clobData = SerialClob(dataString.toCharArray());
    

    There may be a simpler way to instantiate your Clob object, but you will definitely need to serialize your object first. I will leave t to you to see if you can improve on this.