开发者

Saving data when using JPA and BeansBinding

I am currently experimenting with JPA in a desktop application, while using BeansBinding to make the GUI development easier. So far the results are quite good.

As an example application I have a small DB with only one table. I successfully created the entity, the PU. Next I dropped a JTable into the main JFrame and bound it's columns to a JPA query. This works like a charm. So, changes made to the entities reflect in the table, and vice-versa.

Next I wanted to make the table editable, such that the changes are persisted into the DB. The easiest way I came up with was to begin a query and immediately commit it. So, assuming I had a JButton somewhere, do 开发者_JS百科the following on actionPerformed:

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

This works perfectly but it looks oddly wrong to me. I also tried to do this on windowClosing. With success.

But why is it that this worked? I mean, there is no code whatsoever between the transaction begin and commit. And more importantly, is it O.K. to do this?


This somewhat erratic behavior, where the entitymanager persists uncommitted changes without explicitly being told so, arrises because application-manged entity managers are always extended. The JPA specification (in section 3.3) says:

The scope of the persistence context of an application-managed entity manager is extended. It is the responsibility of the application to manage the lifecycle of the persistence context.

So when the bean in question is already in persistence context and you perform a transaction.commit any uncommitted changes will be persisted even without a explicit entitymanager.persist. You can verify this behavior for yourself by clearing the entitymanager (entitymanager.clear) prior to committing the transaction. This will remove the entity from the tx-commit and will cause the transaction to perform no changes to the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜