convert String to Clob and vice versa in Hibernate

hoang nguyen picture hoang nguyen · May 20, 2013 · Viewed 36.2k times · Source

Suppose that I have a Class:

class EventTransaction {
    .....
    private Clob dataXML;

    public Clob getDataXML() {
       return dataXML;
    }

    public void setDataXML(Clob dataXML) {
       this.dataXML = dataXML;
    }
}

And Hibernate mapping xml:

 <property name="dataXML" type="java.sql.Clob">
        <column name="XML" sql-type="CLOB"/>
 </property>

In java code, how to I convert a String to Clob and vice versa to save into to the database:

Ex: EventTransaction et = new EventTransaction();
    String xml = "fdfsafafafa";
    et.setDataXML(convertStringToClob(xml));
    HibernateTemplate.saveOrUpdate(et);

Could you please help how to implement function convertStringToClob(String data);

Thanks,

Answer

Amir Pashazadeh picture Amir Pashazadeh · May 20, 2013

Do this

@Column(name='xml')
@Lob
private String dataXML;

public String getDataXML() {
   return dataXML;
}

public void setDataXML(String dataXML) {
   this.dataXML = dataXML;
}

So there is no need to convert, and everything is done by Hibernate.

I showed it using annotations, the same thing can be done using .hbm.xml files.