Retrieve primary key ID before persisting using sessionfactory in hibernate
Clash Royale CLAN TAG#URR8PPP
Retrieve primary key ID before persisting using sessionfactory in hibernate
I have used below code to get primary key in hibernate before persisting Object. But its inserting duplicate rows in DB.
The issue here I am facing is:
1. I am getting two values for primary key. One when I invoke the flushPerson() method to get 'id' before persisting Person Object.
2. Other when I invoke save method, to save Person object. In this method also 'Id' is getting incremented.
PersonController.java
public Person createNewPerson(String .....)
Person per = new Person();
personManager.flushPerson(per);
RandomNumberGenerator rng = new RandomNumberGenerator();
String randomStrng = rng.generateRandomNumber();
String cientCode = per.getId()+randomStrng;
per.setPersonClientCode(cientCode);
per.setPersonClient();
per.setPersonField();
personManager.save(per);
PersonHibernateDao.java
@Override
public void flushPerson(Person per)
sessionFactory.getCurrentSession().persist(per);
sessionFactory.getCurrentSession().flush();
@Override
public void save(Person per)
sessionFactory.getCurrentSession().save(per);
What am I missing here? I want to save object with only primary key 'id' that is created in flush method and it should insert only one row.
@Navin Gelot i am getting id,But issue is, i am getting two incremented ids. one in, when i invoke flushPerson() ex: assume here 'id' will be 5, here it stores one row with primary key as 5 in DB. Other one in save(Person) where it stores 6 as primary key in DB.
– daisy
Aug 10 at 11:08
Then just use one of flush() and save(), not both.
– P. Soutzikevich
Aug 10 at 14:59
1 Answer
1
Change your save method to:
@Override
public Person save(Person per)
return sessionFactory.getCurrentSession().save(per);
Then, in PersonController
you can do:
PersonController
Person per = new Person();
//whatever Mutators you need
per = personManager.save(per);
//Now you can get id and no duplicate rows will be inserted
if i use only flush(), will transaction be comitted in current session?
– daisy
Aug 13 at 5:45
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
when you saving in your database Person p = personManager.save(per); sout( p.getId() ); print out and check you are getting an id or not if you are get an id then return it :)
– Navin Gelot
Aug 10 at 10:14