-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: setting my own id after specifying generator class="sequence
PostPosted: Mon Jul 25, 2011 4:57 pm 
Newbie

Joined: Mon Jul 25, 2011 4:49 pm
Posts: 3
i have a table which is mapped with following id

<id name="xId" column="X_ID">
<generator class="sequence">
<param name="sequence">X_ID_SEQUENCE</param>

</generator>
</id>

IN some scenarios while inserting a record i need to set my own primary key. we used to do this in the hibernate 3.0.5 using this following method in the Session class.
session.save(xObj, xObj.getXId());

but after upgrading to hibernate 3.2.x this method is not available anymore. What is the alternative for me in the hibernate version 3.2.x

Thanks


Top
 Profile  
 
 Post subject: Re: setting my own id after specifying generator class="sequence
PostPosted: Tue Jul 26, 2011 9:19 am 
Newbie

Joined: Mon Jul 25, 2011 4:49 pm
Posts: 3
I figured out a good way to do this. I created my own SequenceGenerator extending the existing sequence generator. And this new class will be used in the hbm file. The custom sequence genrator will only create sequence when there is not primary key set. I have given the code below

import java.io.Serializable;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.SequenceGenerator;
import org.hibernate.type.Type;

public class CustomSequenceGenerator extends SequenceGenerator {
private String entityName;

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

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;
}

}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.