Storing Large Strings with Hibernate 3
If you want to store a large string in hibernate 3 in a relatively transparent way, the text mapping type is your friend. This will allow you to map a java String type to a database clob type, and store arbitary length large content items. In previous versions (according to google) this took a fair bit of fiddling around, and required custom types (which required much magic to work in a cross platform manner). Thankfully the text mapping type exists, making life much easier.
So in the old school pre 1.5 annotation world, we can take the class with a long string and map it using the code and mapping below:
class Profile {
...
private String bio;
...
public String getBio(){
return bio;
}
public void setBio(String bio){
this.bio=bio;
}
}
and the mapping file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">10485760
<hibernate-mapping>
<class name="Profile" table="profiles">
…
<property name="bio" type="text" length=""/>
</class>
</hibernate-mapping>
This will let you store a large string in hibernate, automatically handling the mapping between clob data and string data. The important parts of the xml snippet above are the type and length attributes. Both are required to ensure that the clob will be created of the right length. The default for the length is 255, which is great when you are storing shortish strings in a varchar, but not so good when you want a large string in a clob.
November 16th, 2007 at 12:36 pm
This is a great feature in terms of simplifying the use of clobs (it’s just a string !) rather than all that streaming business. We use it all the time now. One addition though, is that I believe this requires the Oracle10g JDBC driver, although it does work with Oracle9i. Not sure about 8.
November 16th, 2007 at 12:40 pm
Thanks for the heads up Nicholas. I’ll keep that in mind.
February 25th, 2008 at 1:31 pm
Thank you! You saved the day!