I am trying to build application just using JPA, CDI(OpenWebBeans + Deltaspike JPA module), JSF. I am using CDI deployed on Tomcat in a same manner that I am used to use Spring framework. I have DAO called GenericDAOImpl like this(first few lines):
public abstract class GenericDaoJpa<T> implements GenericDao<T> {
private static final Log logger = LogFactory.getLog(GenericDaoJpa.class);
@Inject
protected EntityManager entityManager;
private Class<T> type;
The EntityManager is injected using DeltaSpike JPA modulehttp://deltaspike.apache.org/jpa.html. This GenericDao is then inherited by concrete DAO(UserDao etc..) which are used by service classes.
For example UserServiceImpl:
public class UserServiceImpl implements UserService {
private static final Log logger = LogFactory.getLog(UserServiceImpl.class);
@Inject
private UserDao userDao;
@Transactional
public void saveUser(UserDto user) throws UserServiceException {
try {
User u = new User(user);
userDao.create(u);
} catch (Exception e) {
logger.error("Error while creating user.", e);
throw new UserServiceException("Error while creating user.");
}
}
}
Using CDI this way both DAO and Service class will have Dependent scope unlike in spring where they would be singleton. Therefore every client will have new instance injected. Should I change scopes on DAO and Service classes to ApplicationScope? But then by the specification I have to make all the classes that are being injected serializable. In case of Dao classes this could be a problem, EntityManager should be then marked as transient? A
I would be glad for any recommendations.
@ApplicationScoped
has no relevance to Serializable
, they're always around and never persist to disk. @SessionScoped
will require serialization due to the behavior of HTTP session objects.
I would recommend using a scope as leaving everything dependent will lead to memory leaks (it's never clear when a @Dependent
object is removed). If your application is fairly stateless, you can use @RequestScoped
. @ApplicationScoped
you need to consider that multiple clients will connect to your instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With