Unexpected exception after detaching entity

Hey everyone! I am currently trying to learn both JPA and Hibernate and i’ve been playing around with some dummy code to understand how everything works. However, i’ve come up with an example that i don’t quite understand. This is the code:

public static void main(String[] args) {
    Map<String, String> options = new HashMap<>();
    options.put("hibernate.show_sql", "true");
    options.put("hibernate.hbm2ddl.auto", "none");

    EntityManagerFactory emf = new HibernatePersistenceProvider()
        .createContainerEntityManagerFactory(new CustomPersistenceUnitInfo(), options);
    
    EntityManager em = emf.createEntityManager();

    try {
        em.getTransaction().begin();
        
        Employee e = new Employee();
        e.setId(1);

        em.persist(e);
        em.detach(e);
        
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

This is the definition of the “Employee” entity (just a dummy Entity i was using):

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @Column(name = "id")
    private int id;

    private String name;  
    private String address;  

    ...getters and setters
}

Taking into account that the “employees” table is empty, what i expect to happen is: an entity of Employee called “e” will be created (transient state). After the persist call the entity will be added to the context, changing its state to managed. Finally, the entity will be removed from the context becoming detached due to the detach call. This would mean that, by the time the commit of the transaction happens, the context should be empty and no entity should be inserted. However, i am getting the following error:

ERROR: HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: possible non-threadsafe access to session.

I know that in the real world it wouldn’t make sense to detach an instance after persisting (without flushing first), but it’s just for understanding the behavior correctly :).

It doesn’t make sense to do that, you figured that out right :slight_smile:

Not sure what else to say. It’s definitely a bug that you get this particular error, but since this is “wrong use”, we probably won’t give much priority to fixing this bug.