I have seen
few hibernate (ORM framework) codes have
always uses saveOrUpdate method to
create a record newly or to update the existing records. Most of the occasions,
we were dam sure that a new record is gonna insert. Such occasions, we can use save method itself. No harm.
Here I am
going to discuss some peculiar scenario where we may need to get the primary
key of the newly added record to send as a response to UI.
For
Example, I am capturing required employee details and creating a new Employee
record. Usually we used to display feedback as Info message in the screen stating “Employee record has been added
successfully.” as a response. Sometime
we may need to display meaningful info message using the generated unique key
for newly created record like “Employee record (1000001)
has been added successfully.” Here, 1000001 is the primary of the newly inserted record.
To address
the above requirement, I have seen few codes (mostly written by beginners),
they used to call the save command (insert query) and use another select
statement which gets you the recent record primary key column. It may work fine
for the single user/thread environment. The same may not be true for multi
thread environment. To address this issue in a multi threaded environment,
below code may be useful for you to achieve the same.
Here, employeeObj is
the hibernate object POJO for Employee Table. If we use hibernate save command,
which will intern returns you the Serializable
interface can cast to
the primary key of the newly inserted record like below.
//Plain Hibernate
Serializable t_pk = t_session.save(employeeObj);
//Hibernate with Spring framework
Serializable t_pk = getHibernateTemplate().save(employeeObj);
Long newEmployeeId = (long) t_pk ;
Any thoughts?
Please drop your comment.
Cheers,
-NjN
No comments:
Post a Comment