1 Reply Latest reply on May 25, 2010 10:10 PM by Raphael Rodrigues

    How Can I turn off GeneratedValue programmatically?

    Raphael Rodrigues Newbie

      Hi Seam experts,


      My application uses Seam and JPA with hibernate provider. I have the situation: I need persist my entitie jpa for two ways.


      1. The first one, uses sequence strategy, like this:


      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "SEQ_OS_MATERIAL")
      


            
      2. The seconde one, don't need strategy for id, because that id was filled in the past. So, i would have that remove GeneratedValue annotation.


      So, my question is: Is there any way to turn off this annotation? How?


      Best Regards,

        • 1. Re: How Can I turn off GeneratedValue programmatically?
          Raphael Rodrigues Newbie

          I solved my problem extending Sequence Gerenator from Hibernate. The workaround works this way.


                 
          1. In my entity
                  @Id
                  @GeneratedValue(generator="SEQ_PESQUISA")
                  @GenericGenerator(name="SEQ_PESQUISA",                  strategy="br.com.activia.commons.persistence.id.CustomSequenceGenerator",parameters = {@Parameter(name="sequence", value="seq_act_pesquisa")})
                  @Column(name="actpesquisaid")
          
          2. custom class generator 
          
          public class CustomSequenceGenerator extends SequenceGenerator {
               
               @Override
               public Serializable generate(SessionImplementor session, Object obj) 
               throws HibernateException {
                    System.out.println("CustomSequenceGenerator");
                    BaseBean<?> myEntity = (BaseBean<?>)obj;
                   //se o id ja foi setado nao precisa gerar da sequence
                    if (myEntity.getId()!=null && myEntity.getId() > 0) {
                     return myEntity.getId();
                   } 
                   else {
                     return super.generate(session, obj);
                   }
               }
          
          }
          
          3. my test case
          
                         Pesquisa p = new Pesquisa();
          //               p.setPesquisaId(170200778L);
                         
                         if (p.getId() != null)
                              em.merge(p);
                         else 
                              em.persist(p);
                         
                         em.flush();