views:

20

answers:

1

I'm new to hibernate. I have a transaction that fails with a HibernateException, yet the table is altered after the commit. Here is the code:

public StoreResult store(Entry entry)
{
    Session session = HibernateUtility.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();

    try
    {           
        String id;

        if (entry.getStatus() == Entry.Status.PUBLISHED)
        {
            id = TitleToURLConverter.convert(entry.getTitle());
        }
        else
        {
            id = "temp_";
        }

        if (entry.getId() == null)
        {
            entry.setId(id);
            session.save(entry);
        }
        else
        {
            session.update(entry);

            session.createQuery("update Entry set id = :newId where id = :oldId")
            .setString("newId", id)
            .setString("oldId", entry.getId())
            .executeUpdate();

            session.refresh(entry);
        }

        transaction.commit();

        return StoreResult.SUCCESS;
    }
    catch (RuntimeException e) 
    {
        transaction.rollback();
        if (e instanceof ConstraintViolationException) return StoreResult.DUPLICATE_ID;

        throw e;
    }
    finally
    {
        session.close();
    }
}

EDIT: Apparently InnoDB does not rollback the transaction on a duplicate key error but only the statement. I would like the transaction to be always rolled back on ANY error.

EDIT2: Disregard this. I was using MyIsam.

+1  A: 

Switching from MyIsam to InnoDB fixed this.

Panayiotis Karabassis