Search This Blog

Monday, 12 September 2011

Id Generators - 6

I shall finish my series on generators with the uuid.hex type. Both uuid.hex and uuid refer to the same generator. The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used).
The UUID is encoded as a string of hexadecimal digits of length 32. This value is generated in Hibernate (unlike guid which is generated in the database). I shall use a simple table here
create table STATE (
 ID varchar(255) not null,
 NAME varchar(255) not null,
 primary key (ID)        
 )
The Java class and mapping document are as below:
public class State {
    private String id;
    private String name;
    //setter-getters
} 
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.model">
    <class name="Town" table="TOWN">
        <id name="id" column="ID" type="string">
            <generator class="uuid.hex" />
        </id>
        <property name="name" type="string">
            <column name="NAME" />
        </property>        
    </class>
</hibernate-mapping> 
On executing code to create a simple state object the logs generated is as below:
2078 [main] DEBUG org.hibernate.jdbc.JDBCContext  - after transaction begin
2078 [main] DEBUG org.hibernate.event.def.DefaultSaveOrUpdateEventListener  - sa
ving transient instance
2078 [main] DEBUG org.hibernate.event.def.AbstractSaveEventListener  - generated
 identifier: 402881d431e8be1e0131e8be21070001, using strategy: org.hibernate.id.
UUIDHexGenerator
2094 [main] DEBUG org.hibernate.event.def.AbstractSaveEventListener  - saving [c
om.model.State#402881d431e8be1e0131e8be21070001]
...
2125 [main] DEBUG org.hibernate.persister.entity.AbstractEntityPersister  - Inse
rting entity: [com.model.State#402881d431e8be1e0131e8be21070001]
2125 [main] DEBUG org.hibernate.jdbc.AbstractBatcher  - about to open PreparedSt
atement (open PreparedStatements: 0, globally: 0)
2125 [main] DEBUG org.hibernate.SQL  - 
    insert 
    into
        STATE
        (NAME, ID) 
    values
        (?, ?)
As can be seen from the above logs, hibernate used its own code to generate uuid identifier, which it assigned to the object being saved. This value was then saved as the id for the new object.

No comments:

Post a Comment