tags:

views:

190

answers:

3

The Hibernate JavaDoc states that Session.update(Object o) would raise an exception if there's already a persistent instance of o, right?

If there is a persistent instance with the same identifier, an exception is thrown.

However, the following code doesn't throw anything when I run it. And I think it should!

Email email = new Email("andre", "girafa", "hi");

Session session = factory.openSession();
Transaction tx = session.beginTransaction();

session.save(email);
session.update(email);
session.update(email);

tx.commit();

// didn't throw... Let's try again

tx = session.beginTransaction();

session.update(email);
session.update(email);

tx.commit();
session.close();

// still nothing! :(

As you can say, twice I try to do multiple update()s, but still Hibernate's taking easy on me.

Anybody has a hunch why?

EDIT: it seems that it would only throw if another equivalent object, for instance, email2 with the same ID as email. I guess the documentation was kinda sloppy there.

+4  A: 

Update in Hibernate is not UPDATE in SQL language. Hibernate handles SQL UPDATEs automatically through state cache in Session object.

But it's only for entities loaded in current session. This method, session.update(object) is meant for attaching object from another tier to current session to track and, possible, update at the end.

In your case it's just an NOOP. It'll sourly throw if:

Email email = new Email("andre", "girafa", "hi");

Session session = factory.openSession();
Transaction tx = session.beginTransaction();

int id = session.save(email);
Email anotherEmail = new Email("", "", "");
anotherEmail.id = id;

session.update(anotherEmail);    // will throw

You could read more about update method semantics on Hibernate reference.

Artem Tikhomirov
A: 

Can you try with a session.flush()? To see if that raises the exception (sometimes commit may not flush data depending on flush mode).

Although I would say the exception is only thrown if the object was updated outside the scope of the current session, let's say by a concurrent client.

Pere Villega
+3  A: 

No error because it's the same instance you're updating.

The error is thrown if a DIFFERENT persistent instance is present in the session and you try to update().

DarkSquid
gets them everytime
Gareth Davis