How to convert a CLOB data type to a String in Hibernate?

Tiny picture Tiny · Aug 14, 2012 · Viewed 37k times · Source

In hibernate (3.2.1.GA), I use the following method to insert CLOB type data into Oracle (10g) database.

Hibernate.createClob(parameters.get("txtCatImage"));

parameters is a Map where all the request parameters have been stored. While retrieving the Clob data type from the database directly something like this entityObj.getCatImage() would not work.

Seen this and this questions but couldn't find the way.

The following is the entity that uses a Clob type property.

public class Category  implements java.io.Serializable {

    private Long catId; // Primary key.
    private Clob catImage; // CLOB type field.
    // Other fields.
    private static final long serialVersionUID = 1L;

    public Category() {}

    // Overloaded constructs + getters + setters + hashcode() + equals() + toString().
}

The Clob field in the database just stores an image file name, in this case.

Answer

Dev picture Dev · Aug 14, 2012

Either call Clob.getSubString(long, int) with appropriate arguments to get the desired String or read the Clob as an InputStream or Reader using Clob.getAsciiStream() or Clob.getCharacterStream().

If the Clob has fewer than 2147483647 (a.k.a. Integer.MAX_VALUE) characters you can do this

Clob clob = ... //Your clob
String clobString = clob.getSubString(0, clob.length());