我对JPA和Facade modell有问题,因为我现在不知道如何使用它。我有一堂课叫做“ Kandidatenstamm”(这是一个实体)。对于此Kandidatenstamm,存在外观和控制器。还有一个抽象外观和抽象控制器。那么,例如在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”为例(原则上与“ Kandidatenstamm”相同)

@EJB
private PersonenstammFacade personenstammFacade;

....

List <Personenstamm> personlist;
personlist = personenstammFacade.findAll();

....
//do what you want with this list

关于java - 如何使用JPA和Facade?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28624390/

10-10 11:39