JPA 2.1: CDI Support

JPA 2.1: CDI Support

In JPA 2.0 or the early version, you can not @Inject a CDI bean into JPA facilities.

Utilize with Apache CODI or JBoss Seam 3, @Inject is supported in Entity Listener classes.

Luckily, JPA 2.1 bring native CDI support.

Have a look at the PostListener in the jpa-converter example.

<pre> public class PostListener { @Inject Logger log; @PrePersist public void prePresist(Object o) { log.info("call prePresist"); if (o instanceof Post) { Post post = (Post) o; final Date created = new Date(); post.setCreated(created); post.setLastModified(created); } } @PreUpdate public void preUpdate(Object o) { log.info("call preUpdate"); if (o instanceof Post) { Post post = (Post) o; post.setLastModified(new Date()); } } } </pre>

In this example, a CDI managed Logger bean war injected into PostListener and was use for tracking the persisting and updating of the Postentity.

<pre> @EntityListeners(PostListener.class) public class Post implements Serializable {...} </pre>

In the Post entity class, apply this EntityListener. When run this project on Glassfish 4, the related log will be displayed in the NetBeans Console view.

But unfortunately, when you try to add the same lifecycle callbacks in the @Entity class, the @Inject annotation does not work, neither in the new introduced @Converter class.

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

https://github.com/hantsy/ee7-sandbox

转载于:https://my.oschina.net/hantsy/blog/182158

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值