I'm working with Spring Roo 1.2.3 on a project, and I need to create a new record of another entity X when the entity Stock is updated. I would do something like this (Similar to a trigger update in database).
@PostPersist
@PostUpdate
private void triggerStock() {
Calendar fechaActual = Calendar.getInstance();
Long cantidad = this.getCantidadStock() - this.getCantidadAnterior();
StockHistory history = new StockHistory();
history.setArticulo(this.getArticulo());
history.setFecha(fechaActual);
history.setCantidad(cantidad);
history.persist();
}
When the application exits from this method throws an error and doesn't save the new element X.
But If I change the last method by:
@PostPersist
@PostUpdate
private void triggerStock() {
Calendar fechaActual = Calendar.getInstance();
Long cantidad = this.getCantidadStock() - this.getCantidadAnterior();
StockHistory history = new StockHistory();
history.setArticulo(this.getArticulo());
history.setFecha(fechaActual);
history.setCantidad(cantidad);
EntityManagerFactory emf = entityManager().getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.setFlushMode(FlushModeType.COMMIT);
em.persist(history);
em.getTransaction().commit();
em.close();
}
This works fine, but I'd like to understand Why I require a new EntityManager for this to work?
Thanks...