Hello.
What I want to do is a standard thing. Insert a record into one table, get the database generated ID of the inserted record, relate this ID in a child table.
Now I have got this working by using some SQL but I thought it would be easier in Hibernate,
is there a better way to do this?
I save my parent object using merge:
Code:
frameworkManager.saveFramework(framework);
//calls this function in the framework manager
//this works fine
public void saveFramework(Framework framein){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try{
session.merge(framein);
session.getTransaction().commit();
}
catch(HibernateException e){
session.getTransaction().rollback();
throw e;
}
}
What I though would happen is after the framework has been saved using merge that i would be able to call framework.getFrameworkID() and this would return the id that has been generated by the database. This is my mapping for the framework ID
Code:
<id name="frameworkID" column="frameworkID">
<generator class="identity" />
</id>
But when I call framework.getFrameworkID() I get 0 like it is before the record has been inserted.
Now to work around this I have run a query to get the max() of the last framework and use this ID. The problem I have with this is locking/transaction issues what if another user enters a new framework before I can get the max() thus:
Code:
public Framework getLastEntered(){
Framework f = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try{
int fid = (Integer)session.createQuery("select max(frameworkID) from Framework").uniqueResult();
f = (Framework)session.get(Framework.class,fid);
session.getTransaction().commit();
}
catch(HibernateException e){
logger.info("--- error getting a single id");
session.getTransaction().rollback();
throw e;
}
return f;
}
I tried with session.refresh() and session.update() after the merge but it made no difference.
Does anyone have any hints or tips on how I might better achieve this. It must be a standard thing in Hibernate as this is always done in CRUD work.
I am using MySQL 5.
Thanks for reading.
cheers
Martin