【发布时间】:2014-10-03 08:44:20
【问题描述】:
我如何实际实例化下面的 JPA 控制器?
我不清楚 Netbeans 创建的 JPA 控制器是如何实际使用的。在这种情况下,我当然很欣赏 Netbeans 向导,它很有趣——我试图了解它是如何工作的,以及为什么它会以这种方式工作。
ejb 模块可以按照以下方式从 Glassfish 注入:
@PersistenceUnit(unitName="JSFPU") //inject from your application server
EntityManagerFactory emf;
@Resource //inject from your application server
UserTransaction utx;
然后,实例化控制器,如下所示:
PersonEntityJpaController pejc = new PersonEntityJpaController(utx, emf); //create an instance of your jpa controller and pass in the injected emf and utx
try {
pejc.create(pe); //persist the entity
我在哪里可以找到有关如何从 Glassfish(在本例中为 Glassfish)注入 PU 以及 @Resource 工作原理的更多信息?我完全不介意阅读来自 Oracle 的 Glassfish for JavaEE 文档或其他参考资料。
Netbeans 生成的控制器:
package db;
import db.exceptions.NonexistentEntityException;
import db.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
public class ClientsJpaController implements Serializable {
public ClientsJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Clients clients) throws RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(clients);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Clients clients) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
clients = em.merge(clients);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = clients.getId();
if (findClients(id) == null) {
throw new NonexistentEntityException("The clients with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Clients clients;
try {
clients = em.getReference(Clients.class, id);
clients.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The clients with id " + id + " no longer exists.", enfe);
}
em.remove(clients);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Clients> findClientsEntities() {
return findClientsEntities(true, -1, -1);
}
public List<Clients> findClientsEntities(int maxResults, int firstResult) {
return findClientsEntities(false, maxResults, firstResult);
}
private List<Clients> findClientsEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Clients.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Clients findClients(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Clients.class, id);
} finally {
em.close();
}
}
public int getClientsCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Clients> rt = cq.from(Clients.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
将在控制器上创建和调用方法的类;它旨在为 Web 模块提供一个队列以从以下位置弹出元素(在此,int's):
package db;
import javax.ejb.Singleton;
@Singleton
public class MySingletonQueue implements RemoteQueue {
private int next = 3; //dummy
private ClientsJpaController cjc; //instantiate how?
@Override
public int getNext() {
return next; //get next int from perhaps another class or method...
}
}
对于上下文,网页用 EL 实例化的 bean:
package dur;
import db.RemoteQueue;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@Named
@SessionScoped
public class MySessionBean implements Serializable {
@EJB
private RemoteQueue mySingletonQueue;
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(MySessionBean.class.getName());
public MySessionBean() {
}
public int getNext() {
log.info("getting next int from remote EJB");
return mySingletonQueue.getNext();
}
}
http://forums.netbeans.org/viewtopic.php?t=47442&highlight=jpa+controller+constructor
【问题讨论】:
-
你现在应该知道的徽章数量是非常离题的。基本上,您在这里证明使用 IDE 生成代码不利于学习体验。根本不这样做 - 自己编写所有代码。这将迫使你去寻找合适的资源来学习 API 和设计理念。 “一本书”是最好的看点;显然你想要 JEE 和 Glassfish 上的一个。
-
同意@Gimby。你不应该写这么糟糕的代码。这样一来,你就学不到什么好东西了。
-
好吧...除了“蹩脚”,你能说得更具体点吗?以一般的方式:)
-
Ok :) 这就是它 - JPA 适合作为 DAO 层,它与控制器是分开的,因此命名
ClientsJpaController非常令人困惑。此外,手动开始/提交事务非常冗长且容易出错 - 最好坚持使用 CMT(Container Managed Transactions)。 (你可以看看this post)。 -
@GrzesiekD。什么是更好的名字?客户DAO?
标签: java jpa netbeans glassfish ejb