Hi all,
I'm trying to generate and assign (via SQL query) a default value to an object property during the object's initial save to the database. I noticed that the Hibernate column mapping element has a 'default' attribute that lets you attach an "SQL expression" - can this be used to assign a default value to a property?
I made a test object & mapping to play with but haven't had much luck so far. Here's what I've created:
Object Code:
Code:
public class Obj{
private int id;
private int myValue;
public Obj(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMyValue() {
return myValue;
}
public void setMyValue(int value) {
this.myValue = value;
}
}
Hibernate Mapping FileCode:
<hibernate-mapping>
<class name="myClass.Obj" table="obj">
<id name="id" column="id" unsaved-value="undefined">
<generator class="sequence">
<param name="sequence">obj_id_seq</param>
</generator>
</id>
<property name="myValue">
<column name="myvalue" not-null="true" default="select max(id) from obj;"/>
</property>
</class>
</hibernate-mapping>
Obj Table in the database:Code:
Table "public.obj"
Column | Type | Modifiers
----------+---------+--------------------------------------------------
id | integer | not null default nextval('obj_id_seq'::regclass)
myvalue | integer | not null
So when I create a new object, assign no value to the property 'value', and save that object, Hibernate inserts and saves '0' as the default value for the property. What I really want it to do is insert the value that's the result of the SQL query in the default attribute of column. Something like:
Code:
insert into obj (myvalue) values ( (select max(id) from obj) );
Is that what the default attribute of the column element is for? If not, any suggestions that would allow me to do something similar? I'm looking for such a solution because can't assign a default value to the column in the database.
Many thanks for any suggestions or help,
-Rob-