EJB3 vs Data Access Objects

2019-04-13 06:26发布

I am working on a project where we need to decide how we are going to expose our persistence layer.

There are currently two options on the table:

1) Use plain DAOs. These would implement an interface and be injected (probably using Weld) in the Business Components which are EJBs. Internally they would use JPA/Hibernate for persistence.

2) Rather than injecting the DAOs using Weld, they would be implemented as EJBs, and injected with @EJB in the Business Components.

Does it really make sense to use EJBs for the persistence layer when we are not using its capabilities (e.g. transaction management - business layer deals with this)?

Is there any performance penalty in using EJB over Weld (or the other way round)?

What option would you think is best?

1条回答
劫难
2楼-- · 2019-04-13 06:43

Using EJBs for a JPA based DAO is a perfectly natural fit.

If the transaction normally starts in your business layer (which are also EJBs as you mention) the transaction will naturally propagate to them. Should you ever want to use the DAO separately, then a transaction will be started for you. You may not use this feature now, but it comes totally free should you ever need it.

Also, should you ever need to a single operation in its own transaction, then this is trivial when your DAOs are EJB based.

Injecting your business EJBs with the DAO EJBs may have a potential performance advantage. As only stubs are injected that delegate to pooled instances, injection is relatively cheap. You can inject your business EJBs with many DAOs that may or may not all be necessary for every call. I'm not 100% sure CDI has this exact same capability. It of course has scoping and conversations but not really stubs to delegate to a pool.

Should you ever need JPA's extended persistence context, then the stateful session bean is practically made for that, otherwise the stateless session bean would be used for DAOs.

That said, CDI is the more modern component model and the current thinking seems to be that EJB will eventually be retrofitted as a set of CDI annotations. Starting to build up a CDI codebase and knowledge now may actually be a long term strategic benefit, and thus bodes for CDI.

So to answer your question more directly: yes it makes sense to use EJBs for the persistence layer, but neither EJB or CDI are absolutely a wrong choice here.

查看更多
登录 后发表回答