Storing Large Strings with Hibernate 3
Thursday, November 15th, 2007
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.