-->
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: how to obtain the key of a bean ?
PostPosted: Wed Mar 27, 2013 12:34 pm 
Beginner
Beginner

Joined: Mon Apr 04, 2011 12:08 pm
Posts: 32
My bean keys are notated either with @Id, @EmbeddedId or @IdClass

I have a bean just created by the user but not yet presisted.
I would like to know before inserting or updating if the bean exist or not.

So I have to do a find(bean.class,beanPk)

so I could create beanPk dynamically by scanning the @Id @EmbeddedId or @IdClass on the bean
I could also save and catch the exception comming from the database

But wouldn't it make sens that hibernate provide a method that just return a beanPk ?


Last edited by mirak on Thu Mar 28, 2013 5:11 am, edited 1 time in total.

Top
 Profile  
 
 Post subject: how to obtain the key of a bean ?
PostPosted: Wed Mar 27, 2013 1:12 pm 
Beginner
Beginner

Joined: Mon Apr 04, 2011 12:08 pm
Posts: 32
I found an ugly and dangerous way to do it
just to prove that hibernate has the tools to do it

Code:
Session currentSession = getHibernateTemplate().getSessionFactory().getCurrentSession();
currentSession.buildLockRequest(LockOptions.NONE).lock(bean);
final Serializable identifier =   currentSession.getIdentifier(bean);
currentSession.evict(bean);
return getHibernateTemplate().get(bean.getClass(), (Serializable) identifier) != null;


without the evict, hibernate returns the just attached instance from the session


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.