Geln Yang
Geln Yang

Reputation: 912

Manually assign value to a hibernate UUID

As we know, in hibernate, configure the generator of a id to "uuid" , then hibernate will auto generate a UUID value to the id field when saving a new object.If configuring the generator to "assigned", the id must be assigned a value before saving a object.

And I found that if configuring the generator to uuid and assigning the id a value manually, the hibernate will change the value to a new UUID one.

My question is, when the generator is configured as uuid, how to manually assign a value to it?

PS: I use spring HibernateDaoSupport to save.

org.springframework.orm.hibernate3.support.HibernateDaoSupport.save(Ojbect obj)

Thanks!

Upvotes: 4

Views: 3058

Answers (1)

axtavt
axtavt

Reputation: 242686

If you need it only in rare special cases, the simpliest way is to issue INSERT queries in native SQL instead of using save().

Alternatively, you can customize generator to achieve the desired behaviour:

public class FallbackUUIDHexGenerator extends UUIDHexGenerator {
    private String entityName;

    @Override
    public void configure(Type type, Properties params, Dialect d)
            throws MappingException {
        entityName = params.getProperty(ENTITY_NAME);
        super.configure(type, params, d);
    }

    @Override
    public Serializable generate(SessionImplementor session, Object object)
            throws HibernateException {            
        Serializable id = session
            .getEntityPersister(entityName, object)
            .getIdentifier(object, session);       

        if (id == null)
            return super.generate(session, object);
        else
            return id;
    }
}

and configure Hibernate to use it by setting its fully qualified name as strategy.

Upvotes: 13

Related Questions