java persistence with jpa 2.1_JPA 2.1: Unsynchronized Persistence Contexts

JPA 2.1: Unsynchronized Persistence Contexts

In JPA 2.0 and the early version, any change of the data will be synchronized into database at the transaction is committed.

JPA 2.1 introduced a synchronization attribute in @PersistenceContext annotation when it's value is SynchronizationType.UNSYNCHRONIZED, you have to call joinTransaction to synchronize the data into database manually.

 @PersistenceContext(synchronization = SynchronizationType.UNSYNCHRONIZED) EntityManager em; 

Compare the two methods.

 public void save() { final Comment comment = new Comment(this.commentBody); comment.setPost(this.post); this.post.getComments().add(comment); em.merge(this.post); this.commentBody=""; } public void saveWithJoinTransaction() { final Comment comment = new Comment(this.commentBody); comment.setPost(this.post); this.post.getComments().add(comment); em.joinTransaction(); em.merge(this.post); this.commentBody=""; } 

Conceptually, this feature is a little similar with Hibernate's FlushMode. If you have used Seam 2, you could be impressed of the Hibernate FlushMode feature. In Seam 2, it allow you flush data manually in some case. For example, perform a series of steps in a flow, the data change will be cached and be committed in the last step, and allow you give up any change if exit the flow.

The sample codes are hosted on my github.com account, check out and play it yourself.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值