How to properly finalize session and transaction at the end of request?

I am learning Vaadin and stucking at the problem for a while. I have a table populated with data using jpa (mysql / hibernate). Clicking item in the table popup a form to edit the entity. Everything work as expected. The problem appears when i click on the item again to edit and got an exception: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction

The following code is my form to edit entity. What do i need to do to after persist or merge my entity correctly?

	@Override
	public void buttonClick(ClickEvent event)
	{
		Button source = event.getButton();
		
		if(source == save)
		{
			try 
			{
	            commit();
	            BeanItem<Invoice>beanItem = (BeanItem<Invoice>) getItemDataSource();
	            Invoice invoice = ((BeanItem<Invoice>) getItemDataSource()).getBean();
	            
	            if(addOrEdit)
	            {
	            	parentDataSource.addBean(invoice);
	            	invoice.persist();
	            }
	            else
	            {
                        invoice.merge();
	            }
	            this.getApplication().getMainWindow().removeWindow(this.getWindow());
	        } 
			catch (EmptyValueException e) 
	        {

	        }
		}
		else if(source == cancel)
		{
			this.getApplication().getMainWindow().removeWindow(this.getWindow());
		}
	}

I also took a look in session-per-request pattern with hibernate. Is this related to my problem? if yes, is there a simpler alternative that don’t have to do with hibernate.

Just a guess, but if I remember correctly Hibernates merge() method returns the merged instance, it doesn’t edit in-place. So the second time you are using the Invoice Bean it’s already old. Without seeing your JPA methods it’s impossible to tell what goes wrong, though.

I’ve solved this issue in the past by using reflection to swap all fields from the new, merged object to the old. It might qualify for ‘hack’ status, but it did work for me.

Maybe you should take a look at JPAContainer. It’s a commercial addon but those are free to use under certain circumstances …