I have problem with using entityManager managed by EJB Container.
In my ear i have 3 modules:
-domain - There are Entity Classes and DAO Implementations with Interfaces as EJBs.
-services - There I would have logic related with processing requests, invoking bussiness exceptions based on libraries exceptions (for example database exceptions).
-Rest Services - There I would have rest endpoints to receive and send some business objects.
So the main problem is with using EJBs in services layer, I can declare Rest endpoint class, service class, and DAO Class as EJBs. But that way i can't catch exceptions related with database, because as I red I get transactionRollback exception in my EJB container provided by WildFly and this exception is existing on commiting transaction.
I thought about removing @Stateless annotation from service class, but when I do it EJB container don't inject entityManager in my DAO class. Also I tried using @Inject annotation in service class, but still get the same NullPointer exception on entityManager in Dao Class.
Below I am adding sample code implementations in my project :
DAO Class:
@Stateless
public class CardDaoImpl implements CardDao {
@PersistenceContext(unitName = "test")
protected EntityManager em;
public CardBase addCardToDatabase(CardBase card) {
em.persist(card);
return card;
}
Service Class (here I want to handle businessExceptions):
@Stateless
public class TestService implements TestServiceIf {
@EJB(beanInterface = CardDao.class)
private CardDao dao;
@Override
public CardBase addCard(CardBase card) {
dao.addCardToDatabase(card);
return card;
}
}
Rest Endpoint Class:
@Stateless
@Path("/test")
public class Test {
@EJB(beanInterface = TestServiceIf.class)
private TestServiceIf service;
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public String addCard() {
CardBase card = new SampleCard();
//Setting card object fields//
service.addCard(card);
return "Hello";
}
}
This is only one solution which I've discovered. But what's with throwing my businnesExceptions? Maybe it's not a good practice to throwing them in this service layer?