Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert String to Clob and vice versa in Hibernate

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,

like image 354
hoang nguyen Avatar asked May 20 '13 02:05

hoang nguyen


2 Answers

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.

like image 128
Amir Pashazadeh Avatar answered Sep 23 '22 05:09

Amir Pashazadeh


Here is code I made a long time ago to convert a Clob to a String. It's meant to be used in a utility class.

    public static String convertClobToString(Clob clob) throws IOException, SQLException {
            Reader reader = clob.getCharacterStream();
            int c = -1;
            StringBuilder sb = new StringBuilder();
            while((c = reader.read()) != -1) {
                 sb.append(((char)c));
            }

            return sb.toString();
     }

And if I am not mistaken, to create a Clob you would do something like this

     Clob myClobFile = new SerialClob("my string".toCharArray());
like image 43
george_h Avatar answered Sep 24 '22 05:09

george_h