I want to be able to set a default value if nothing is specified for that field.
After reading some topics on this forum I've understood that I can use a UserType to do that.
<property name="origin" column="ORIGIN">
<type name="util.test.DefaultValueUserType">
<param name="defaultValue">A default value</param>
</type>
</property>
Here is also a fragment from the class DefaultValueUserType
public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index)
throws HibernateException, SQLException {
if ( value == null ) {
Hibernate.STRING.nullSafeSet(preparedStatement, defaultValue, index);
}
else {
Hibernate.STRING.nullSafeSet(preparedStatement, value, index);
}
public Class returnedClass() {
return String.class;
}
I've used SchemaExport to generate DDL.
create table TABLE_NAME (ID varchar2(255) not null, ORIGIN varchar2(255), primary key (ID))
I've used PojoExporter to generate the POJO files.
public class Acronym implements java.io.Serializable {
private DefaultValueUserType origin;
public DefaultValueUserType getOrigin() {
return this.origin;
}
public void setOrigin(DefaultValueUserType origin) {
this.origin = origin;
}
}
Now I want to insert two new records: one with a defult value and one with a value set up by me.
Acronym acronym = new Acronym();
hibernateSession.save(acronym);
// that was the one with the default value
Acronym acronym = new Acronym();
acronym.setOrigin(???);
// here is my problem because it expects a DefaultValueUserType object
hibernateSession.save(acronym);
hibernateSession.flush();
Any ideeas/advices ? Thanks. If any details needed please ask.
|