Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java EE DAO without EJB

Tags:

jpa

ejb

ejb-3.1

Is it possible to create a DAO in Java EE environment, which uses JPA, but does not need to be a Stateless bean? I am asking because I have a huge number of EJBs, just because I need a few @Resources in the DAOs, i.e. EntityManager and so on.

What would you recommend as a way to simplify DAOs in huge project, it seems to me that having a full EJB (instead of a simple object) for a DAO is eccessive.

DAOs are accessed both from other EJBs and from servlets.

like image 245
bozo Avatar asked Jun 02 '26 06:06

bozo


1 Answers

It's possible, but not recommended, to inject an EntityManager into other types of beans (like e.g. CDI managed beans) along with a UserTransaction and then manually manage your transactions.

In Java EE 7, JTA 1.2 contributes CDI compatible extensions for declarative transactions just like EJBs have, but at the moment there's no final release of any Java EE 7 AS yet.

it seems to me that having a full EJB (instead of a simple object) for a DAO is excessive.

Why do you think that? A "full" EJB is probably more lightweight than any other alternative, and almost certainly more lightweight than any home cooked thing you can come up with based on an EntityManager.

Don't forget that EJB beans share their resources automatically and that injection points only get proxies. If you mainly use stateless EJB beans, those proxies are akin to URLs, and not the "real" beans. This makes stateless and local EJB beans incredibly lightweight to inject.

Meaning, if you have a given Service where you inject (say) 10 DAOs, that each have an injected EntityManager, and during a given call 3 DAOs are invoked then only 3 beans are actually used and only 1 EntityManager instance. It really is rather efficient.

like image 164
Arjan Tijms Avatar answered Jun 04 '26 13:06

Arjan Tijms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!