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