Saving data using JPA and BeansBinding

I am currently experimenting with JPA in a desktop application using BeansBinding to simplify GUI development. So far, the results are not bad.

As an example of an application, I have a small database with only one table. I have successfully created an object, PU. Then I removed the JTable in the main JFrame and bound its columns to the JPA request. It works like a charm. Thus, changes made to objects are reflected in the table, and vice versa.

Next, I wanted to make the table editable so that the changes were saved in the database. The easiest way I came across was to start a request and make it immediately. So, assuming I have JButton, do the following on actionPerformed :

 private void saveClicked(java.awt.event.ActionEvent evt) { this.myEntityManager.getTransaction().begin(); this.myEntityManager.getTransaction().commit(); } 

This works fine, but to me it looks weirdly wrong. I also tried to do this on windowClosing . Successfully.

But why did it work? I mean, there is no code between the begin and commit transaction. And more importantly, is it OK to do this?

+4
source share
1 answer

This is a somewhat erratic behavior in which the entitymanager saves uncommitted changes without explicitly reporting this, because application entity administrators are always extended. The JPA specification (in section 3.3) states:

The persistence context area of ​​the control object managed by the application manager is expanded. It is the responsibility of the application to manage the life cycle of the conservation context.

Therefore, when the bean in question is already in the context of persistence and you execute transaction.commit , any uncommitted changes will be saved even without an explicit entitymanager.persist , you can check this behavior for yourself by clearing the entitymanager ( entitymanager.clear ) before making the transaction. This will remove the object from tx-commit and cause the transaction to not make any changes to the database.

+2
source

Source: https://habr.com/ru/post/1301250/


All Articles