Which CDI scope should be preferred for a JPA repository
How do I determine the appropriate CDI scope for a JPA repository like below?
@Transactional
public class CategoryRep extends EntityRepository<Integer, Category> {
private static final long serialVersionUID = 856370976984333182L;
public List<Category> getAllCategories() {
// TODO
}
public List<Post> getAllPostsOfCategory(Integer categoryId) {
// TODO
}
@Transactional(value = TxType.REQUIRES_NEW, rollbackOn = RuntimeException.class)
public void createCategory(final String name, final String description)
throws DaoJpaException {
// TODO
}
}
I can think of only two CDI scopes:
All other CDI-scopes aren't appropriate in my opinion:
entityManager.clear()
will cause that all instances of all current sessions will be detached as well. Additionally this single repository have to handle all incoming requests. Possibly this scope is appropriate for read only repository? @Dependent
. So, are there any best practices known to this issue?
To describe all of the options
So I would go with either
So if I were you I would go for Request scope repository, it's the most easier option and you will avoid all the problems that way.
You should use @ApplicationScoped.
An EntityManager should be used per request and not reused.
At the begging of the request you create the entityManager, when it finishes commit or rollback it.
@Dependent will have the same scope of its 'host', if you inject it in a @RequestScoped and bean will have the same scope.
@SessionScoped should be used only for small data (like user login and permissions).
链接地址: http://www.djcxy.com/p/62212.html上一篇: 跨两个GF服务器部署JSF ViewScoped CDI Bean不一致
下一篇: JPA存储库应该首选哪个CDI范围