-->
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.  [ 1 post ] 
Author Message
 Post subject: How do i use transaction in IdentifierGenerator?
PostPosted: Sun May 22, 2011 11:04 am 
Newbie

Joined: Sun May 22, 2011 10:46 am
Posts: 1
Hello!

I'm new to Hibernate and try to write my own id generator based on IdentifierGenerator. I need an id of type String, but unfortunately MySQL does not support "nextval". So I try to do a SELECT first, increment my simulated sequence number and then put it back with an UPDATE query.

I want to use transactions for these two queries, but I don't know how. I have done a SELECT with entity manager and em.createQuery before, but I don't know how to UPDATE and do transactions in IdentifierGenerator. Do I have to work with this "SessionImplementor session" object or can I create my own entity manager as usual?

My code is based on this snippet:
http://snipt.net/belano/custom-hibernat ... r-id-field

Code is still work in progress...
Code:
public class MyGenerator implements IdentifierGenerator
{
  @Override
  public Serializable generate(SessionImplementor session, Object object) throws HibernateException
  {
    String prefix = "id-";
    int id = 0;

    // Is this the right way or do I have to use session argument somehow?
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
    EntityManager em = emf.createEntityManager();

    em.getTransaction().begin();

    try
    {
      Query selectQuery = em.createQuery("SELECT counter AS next_value FROM sequence_numbers WHERE sequence='my_id'");
      List<Integer> idList = (List<Integer>)selectQuery.getResultList(); // should work up to here

      if (idList.isEmpty())
      {
        id = 0;
      }
      else
      {
        id = idList.get(0) + 1;
      }

      Query updateQuery = em.createQuery("UPDATE sequence_numbers SET counter=" + id + " WHERE sequence='my_id'");
      // how do I send UPDATE query?

      String code = prefix + StringUtils.leftPad("" + id, 27, '0');

      return code;

     // end transaction, close em and emf, end try..catch and so on
  }
}


I would appreciate any help, since I'm not very familiar with Hibernate internals yet.

Tnx.


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

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.