如何在下面实际实例化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
在哪里可以找到有关如何注射PU的更多信息,在本例中为Glassfish,以及@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...
}
}
for context,网页用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
答案 0 :(得分:2)
答案很简单:
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书或阅读一些体面的指南。