Your are right, I should have used the object states vocabulary from the start.
I´ve made a simple class to illustrate the scenario of my second post:
Code:
package net.bpfurtado.sessionlocktest;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.LockMode;
import org.hibernate.Session;
public class Main
{
private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
public static void main(String[] args)
{
lockFirstDetachedThenPersistent();
lockFirstPersistentThenDetached(); //Here I get the 'NonUniqueObjectException' exception
}
private static void lockFirstDetachedThenPersistent()
{
Book detached = createDetached();
HibernateUtil.beginTransaction();
Book persistent = (Book) HibernateUtil.getSession().load(Book.class, detached.getId());
HibernateUtil.getSession().lock(detached, LockMode.NONE);
HibernateUtil.getSession().lock(persistent, LockMode.NONE); //Here I don´t get the error and I can do anything I want with the detached or transient instance.
detached.setTitle("Detached updated " + sdf.format(new Date()));
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
}
private static void lockFirstPersistentThenDetached()
{
Book detached = createDetached();
HibernateUtil.beginTransaction();
Book persistent = (Book) HibernateUtil.getSession().load(Book.class, detached.getId());
HibernateUtil.getSession().lock(persistent, LockMode.NONE);
HibernateUtil.getSession().lock(detached, LockMode.NONE); //Here I get the 'NonUniqueObjectException' exception
detached.setTitle("Detached updated " + sdf.format(new Date()));
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
}
private static Book createDetached()
{
Book detached = new Book();
detached.setTitle("Detached " + sdf.format(new Date()));
HibernateUtil.beginTransaction();
Session session = HibernateUtil.getSession();
session.save(detached);
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
return detached;
}
}
The 'NonUniqueObjectException' exception occurs at the invocation of the second statement of main method. Better saying at the 'lockFirstPersistentThenDetached' operation.
A simple eclipse project with this example can be found here
http://www.bpfurtado.net/files/sessionlocktest.
The .java files are in the same location if you don´t want to download the project.
Thanks in advance.