views:

44

answers:

1

My "HelloJPA" code (below) tries to store an Employee in a datastore. However, any attempt to read the persisted object after committing the (resource local) transaction is rewarded with an "IllegalStateException":

Employee employee = ...
EntityManagerFactory factory =
    Persistence.createEntityManagerFactory( "HelloJPA", System.getProperties() );
EntityManager manager = factory.createEntityManager();
EntityTransaction transaction = manager.getTransaction();
try {
    transaction.begin();
    manager.persist( employee );
    transaction.commit();
} finally {
    if (transaction.isActive()) {
        transaction.rollback();
    }
    manager.close();
}
System.out.println("Employee id == " + employee.getId() ); //<< IllegalStateException

OK, I guess, the manager took possession of my new-allocated employee object and it became unavailable once I committed the transaction. But then, what's the common idiom to implement this simple operation, i.e., writing an object all the way to the datastore while still keeping read-only access to it? The documentation (tutorials or API references) doesn't address this specifically, and the code samples I've found that use resource local transactions never seem to try to read the object after committing ... But surely there must be a trivially simple way to do it??

Thanks in advance for any help/pointers on this!

A: 

Your employee becomes detached after closing the entity manager but there is nothing that forbids accessing the Id annotated property of a detached entity. IOW, your code is correct and works with Hibernate and EclipseLink. Maybe search in OpenJPA's Jira for an existing issue or open a new one.

Pascal Thivent