Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need for an unsaved-value attribute in hibernate?

Tags:

hibernate

What is the need for an unsaved-value attribute?

<id name="userid" column="userid" type="java.lang.Long" unsaved-value="null">   
  <generator class="sequence">
    <param name="sequence">dmuseridseq</param>
  </generator> 
</id>
like image 811
suresh Avatar asked Jan 07 '12 11:01

suresh


2 Answers

It is explained in this brilliant article:

The Hibernate mapping file indicates that the id field on Person is the database ID (i.e. it is the primary key in the PERSON table). Within the id tag is an attribute, unsaved-value="null", that tells Hibernate to use the id field to determine whether a Person object has been previously saved or not. ORM frameworks must make this distinction to know whether they should save the object with a SQL INSERT or UPDATE statement. In this case, Hibernate assumes that the id field starts out null on new objects and is assigned when they are first saved.

Also, you can read about "unsaved-value" in the book "Java Persistence with Hibernate":

enter image description here

like image 103
jhegedus Avatar answered Dec 01 '22 19:12

jhegedus


http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html

unsaved-value (optional - defaults to a "sensible" value): an identifier property value that indicates an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session.

In your example, unsaved-value="null" seems pretty pointless, since I suspect the "sensible default" for a Long is null.

It's more useful for primitive types (e.g. int), which cannot be null, and the default unsaved-value of 0 may be undesirable in some applications (0 being a perfectly valid number value).

like image 43
skaffman Avatar answered Dec 01 '22 20:12

skaffman