我对JPA和Facade modell有问题,因为我现在不知道如何使用它。我有一个班叫"Kandidatenstam"(这是一种天赋)。对于这个Kandidatenstam,存在一个门面和控制器。还有一个抽象立面和一个抽象控制器。那么,我必须在bean中做什么呢?例如,从id为4的数据库中获取对象?
这是我的代码
抽象立面
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 void edit(T entity) {
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) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Kandidatenstamm立面
@Stateless
public class KandidatenstammFacade extends AbstractFacade<Kandidatenstamm> {
@PersistenceContext(unitName = "ffswebadministrationPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public KandidatenstammFacade() {
super(Kandidatenstamm.class);
}
}
好吧,我自己搞定了。只进行EJB注入并使用Facade。这里的例子是"Personenstamm"(原则上与"Kandidatenstam"相同)
@EJB
private PersonenstammFacade personenstammFacade;
....
List <Personenstamm> personlist;
personlist = personenstammFacade.findAll();
....
//do what you want with this list