-->
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.  [ 3 posts ] 
Author Message
 Post subject: [SOLVED] Selectively disable generation of a new ID
PostPosted: Wed Mar 31, 2010 11:17 am 
Newbie

Joined: Wed Mar 31, 2010 11:02 am
Posts: 3
The problem is: We have a large application, and 99.9% of time, the automatic ID generation works perfectly; recently, though, we had to implement an application that pulls data from another application through a webservice and saves it to the local database. Both use exactly the same persistent classes. I need the client application to locally store data pulled from the server with no modification, not even ID's. The problem is: no matter what you do, during inclusion Hibernate is simply generating a brand new ID, no questions asked.

Is there any way to tell Hibernate to sometimes, just sometimes, skip the ID generation during an inclusion and just use whatever ID the object currently has?

For reference, this is the base persistent class:

Code:
/**
* Classe base das classes persistentes do sistema.
*
* @author Haroldo
*/
@MappedSuperclass
public abstract class PersistentImpl implements Persistent, Comparable {
   private Long id;

   private Date version;

   /**
    * @see com.ats.framework.pojo.Persistent#getId()
    */
   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   public Long getId() {
      return this.id;
   }
   /**
    * @see com.ats.framework.pojo.Persistent#setId(java.lang.Long)
    */
   public void setId(Long id) {
      this.id = id;
   }

   /**
    * Data/hora/minuto/segundo/milésimo da última modificação.<br>
    * Usado para implementação do lock otimista.
    *
    * @see com.ats.framework.model.pojo.Persistent#getVersion()
    */
   @Version
   @Column(nullable=false)
   @Temporal(TemporalType.TIMESTAMP)
   public Date getVersion() {
      return version;
   }
   /**
    * @see com.ats.framework.model.pojo.Persistent#setVersion(java.util.Date)
    */
   public void setVersion(Date version) {
      this.version = version;
   }

   /**
    * Necessário para comportar-se corretamente quando incluído
    * dentro de um Set.
    *
    * @see java.lang.Object#equals(java.lang.Object)
    */
   public boolean equals(Object obj) {
      if (this == obj) {
         return true;
      }
      if ((obj != null) && (obj instanceof Persistent) &&
            (this.getId() != null) && (((Persistent)obj).getId() != null)) {
         return this.getId().equals(((Persistent)obj).getId());
      }
      return false;
   }

   public int compareTo(Object o) {
      if (this.equals(o)) {
         return 0;
      }
      if ((o != null) && (o instanceof Persistent) &&
            (this.getId() != null) && (((Persistent)o).getId() != null)) {
         return this.getId().compareTo(((Persistent)o).getId());
      }
      return 0;
   }

   /**
    * Necessário para comportamento correto dentro de HashSet e HashMap.
    *
    * @see java.lang.Object#hashCode()
    */
   public int hashCode() {
      if (this.getId() == null) {
         return 0;
      }
      return this.getId().hashCode();
   }

   /**
    * Apenas para depuração.
    *
    * @see java.lang.Object#toString()
    */
   public String toString() {
      StringBuffer sb = new StringBuffer(super.toString());
      sb.append(" id=").append(this.getId());
      return sb.toString();
   }

}


And this is the class I'm currently using for the tests:

Code:
/**
* Classe de Persistência do Pais
*
* @author Mauricio Monteiro
*/
@Entity
public class Pais extends CadastroBase {
   private Collection<Estado> estados;

   /**
    * @return Returns the estados.
    */
   @OneToMany(fetch=FetchType.LAZY, mappedBy="pais")
   @OrderBy("uf")
   @XmlTransient
   public Collection<Estado> getEstados() {
      return this.estados;
   }

   /**
    * @param estados The estados to set.
    */
   public void setEstados(Collection<Estado> estados) {
      this.estados = estados;
   }
}


Last edited by haroldo-ok-ats on Wed Mar 31, 2010 2:37 pm, edited 3 times in total.

Top
 Profile  
 
 Post subject: Re: Selectively disable generation of a new ID
PostPosted: Wed Mar 31, 2010 12:46 pm 
Newbie

Joined: Wed Mar 31, 2010 11:02 am
Posts: 3
Okay, problem solved: Using merge() instead of save() made Hibernate perform as required.
[UPDATE] No, it's not solved. While the object's ID remains unmodified, Hibernate silently writes it to the database with a different ID.

References:
http://stackoverflow.com/questions/89439/bypass-generatedvalue-in-hibernate
http://stackoverflow.com/questions/2108178/id-generatedvalue-but-set-own-id-value


Top
 Profile  
 
 Post subject: Re: Selectively disable generation of a new ID
PostPosted: Wed Mar 31, 2010 2:36 pm 
Newbie

Joined: Wed Mar 31, 2010 11:02 am
Posts: 3
Solved by creating a custom IdentifierGenerator.

References:
http://www.experts-exchange.com/Programming/Languages/Java/Q_22018170.html
http://community.jboss.org/wiki/Customsequences
http://blog.anorakgirl.co.uk/?p=43

The code I've used:

Code:
public class IdKeepingSequenceGenerator extends SequenceGenerator  {
   @Override
   public Serializable generate(SessionImplementor session, Object object)
         throws HibernateException {
      if (object instanceof Persistent) {
         Persistent persistent = (Persistent)object;
         if (persistent.getId() != null && persistent.getId() > 0) {
            return persistent.getId();
         }
      }
      return super.generate(session, object);
   }
}


Code:
@Id
@GenericGenerator(name="seq_id",
                           strategy="com.ats.framework.model.util.IdKeepingSequenceGenerator")
@GeneratedValue(generator="seq_id")
public Long getId() {
   return this.id;
}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 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.