[英]instantiate JPA controller by injecting from glassfish
我实际上如何实例化下面的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中注入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
):
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
答案很简单:
package db;
import javax.ejb.Singleton;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
@Singleton
public class MySingletonQueue implements RemoteQueue {
private int next = 3;
private ClientsJpaController cjc;
@PersistenceUnit
private EntityManagerFactory emf;
@Resource
private UserTransaction utx;
@PostConstruct
public void initBean() {
// Instantiate your controller here
cjc = new ClientsJpaController(utx, emf);
}
// rest of the class ...
}
但是请记住,尽管它可以工作,但是您所做的事情却非常混乱且难以维护,被认为是不正确的做法 。
一些忠告:
ClientsJpaController
(也可以考虑将其重命名为ClientDAO
) Clients
实体是复数形式,应该是单数形式,因为它代表单个客户,不是吗? catch (Exception ex) {
,因为它是所有异常的根源。 而是仅捕获最具体的异常。 因此,例如,您的编辑功能可以简化为:
public Client edit(Client client) {
return em.merge(client);
}
您肯定应该看一看EJB / JPA书籍或阅读一些体面的指南。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.