我想问在访问EJB Session Bean时使用Facade Pattern的原因是什么。在我的 Netbeans 6.9.1 中,如果我这样做New
> Sessions Bean for Entity Classes
,假设我选择了User
实体,那么 Netbeans 将生成此代码
AbstractFacade.java
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public T edit(T entity) {
return getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
...
}
public int count() {
...
}
和
UserFacade.java
package com.bridgeye.ejb;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class UserFacade extends AbstractFacade<User> {
@PersistenceContext(unitName = "Bridgeye2-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public UserFacade() {
super(User.class);
}
}
我想问这有什么好处。如果我有 10 个实体,那么 Netbeans 将生成 10 个 Facade 类以及 AbstractFacade。这对我来说似乎有点矫枉过正。假设在我的托管 bean 中的某个地方,我必须这样persist
做User
,School
然后我必须这样做
someManagedBean.java
...
@EJB
private UserFacade userEJB;
@EJB
private SchoolFacade schoolEJB;
...
public void someMethod(User user, School school){
...
userEJB.create(user);
schoolEJB.create(school);
}
这是正确的做法吗?