2014-03-29 143 views
0

我有後續類....JPA控制器與依賴注入

數據庫EntityBean的

@Entity 
@Table(name = "tb_clientes") 
@XmlRootElement 
@NamedQueries({ 
    @NamedQuery(name = "TbClientes.findAll", query = "SELECT t FROM TbClientes t"), 
    @NamedQuery(name = "TbClientes.findById", query = "SELECT t FROM TbClientes t WHERE t.id = :id"), 
    @NamedQuery(name = "TbClientes.findByNomeCliente", query = "SELECT t FROM TbClientes t WHERE t.nomeCliente = :nomeCliente"), 
    @NamedQuery(name = "TbClientes.findByTelefone1", query = "SELECT t FROM TbClientes t WHERE t.telefone1 = :telefone1"), 
    @NamedQuery(name = "TbClientes.findByTelefone2", query = "SELECT t FROM TbClientes t WHERE t.telefone2 = :telefone2"), 
    @NamedQuery(name = "TbClientes.findByTelefone3", query = "SELECT t FROM TbClientes t WHERE t.telefone3 = :telefone3"), 
    @NamedQuery(name = "TbClientes.findByEmail1", query = "SELECT t FROM TbClientes t WHERE t.email1 = :email1"), 
    @NamedQuery(name = "TbClientes.findByEmail2", query = "SELECT t FROM TbClientes t WHERE t.email2 = :email2"), 
    @NamedQuery(name = "TbClientes.findByContato", query = "SELECT t FROM TbClientes t WHERE t.contato = :contato"), 
    @NamedQuery(name = "TbClientes.findByObs", query = "SELECT t FROM TbClientes t WHERE t.obs = :obs")}) 
public class TbClientes implements Serializable { 
    private static final long serialVersionUID = 1L; 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Basic(optional = false) 
    @Column(name = "id") 
    private Integer id; 
    @Basic(optional = false) 
    @NotNull 
    @Size(min = 1, max = 100) 
    @Column(name = "NomeCliente") 
    private String nomeCliente; 
    @Size(max = 15) 
    @Column(name = "Telefone1") 
    private String telefone1; 
    @Size(max = 15) 
    @Column(name = "Telefone2") 
    private String telefone2; 
    @Size(max = 15) 
    @Column(name = "Telefone3") 
    private String telefone3; 
    @Size(max = 100) 
    @Column(name = "Email1") 
    private String email1; 
    @Size(max = 100) 
    @Column(name = "Email2") 
    private String email2; 
    @Size(max = 100) 
    @Column(name = "Contato") 
    private String contato; 
    @Size(max = 200) 
    @Column(name = "Obs") 
    private String obs; 
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idCliente") 
    private Collection<TbLogemail> tbLogemailCollection; 

    public TbClientes() { 
    } 

    public TbClientes(Integer id) { 
     this.id = id; 
    } 

    public TbClientes(Integer id, String nomeCliente) { 
     this.id = id; 
     this.nomeCliente = nomeCliente; 
    } 

    public Integer getId() { 
     return id; 
    } 

    public void setId(Integer id) { 
     this.id = id; 
    } 

    public String getNomeCliente() { 
     return nomeCliente; 
    } 

    public void setNomeCliente(String nomeCliente) { 
     this.nomeCliente = nomeCliente; 
    } 

    public String getTelefone1() { 
     return telefone1; 
    } 

    public void setTelefone1(String telefone1) { 
     this.telefone1 = telefone1; 
    } 

    public String getTelefone2() { 
     return telefone2; 
    } 

    public void setTelefone2(String telefone2) { 
     this.telefone2 = telefone2; 
    } 

    public String getTelefone3() { 
     return telefone3; 
    } 

    public void setTelefone3(String telefone3) { 
     this.telefone3 = telefone3; 
    } 

    public String getEmail1() { 
     return email1; 
    } 

    public void setEmail1(String email1) { 
     this.email1 = email1; 
    } 

    public String getEmail2() { 
     return email2; 
    } 

    public void setEmail2(String email2) { 
     this.email2 = email2; 
    } 

    public String getContato() { 
     return contato; 
    } 

    public void setContato(String contato) { 
     this.contato = contato; 
    } 

    public String getObs() { 
     return obs; 
    } 

    public void setObs(String obs) { 
     this.obs = obs; 
    } 

    @XmlTransient 
    public Collection<TbLogemail> getTbLogemailCollection() { 
     return tbLogemailCollection; 
    } 

    public void setTbLogemailCollection(Collection<TbLogemail> tbLogemailCollection) { 
     this.tbLogemailCollection = tbLogemailCollection; 
    } 

    @Override 
    public int hashCode() { 
     int hash = 0; 
     hash += (id != null ? id.hashCode() : 0); 
     return hash; 
    } 

    @Override 
    public boolean equals(Object object) { 
     // TODO: Warning - this method won't work in the case the id fields are not set 
     if (!(object instanceof TbClientes)) { 
      return false; 
     } 
     TbClientes other = (TbClientes) object; 
     if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { 
      return false; 
     } 
     return true; 
    } 

    @Override 
    public String toString() { 
     return "br.com.capixapao.domain.TbClientes[ id=" + id + " ]"; 
    } 

} 

和一個控制器類(如DAO):

public class TbUsuariosJpaController implements Serializable { 

    private EntityManagerFactory emf = null; 

    public TbUsuariosJpaController(EntityManagerFactory emf) { 
     this.emf = emf; 
    } 
    public TbUsuariosJpaController() 
    { 
     EntityManagerFactory emf = Persistence.createEntityManagerFactory("br.com.capixapao_capixapao_war_1.0PU"); 
     this.emf = emf; 
    } 

    public EntityManager getEntityManager() { 
     return emf.createEntityManager(); 
    } 

    public void create(TbUsuarios tbUsuarios) throws PreexistingEntityException, Exception { 
     EntityManager em = null; 
     try { 
      em = getEntityManager(); 
      em.getTransaction().begin(); 
      em.persist(tbUsuarios); 
      em.getTransaction().commit(); 
     } catch (Exception ex) { 
      if (getTbUsuariosById(tbUsuarios.getUserName()) != null) { 
       throw new PreexistingEntityException("TbUsuarios " + tbUsuarios + " already exists.", ex); 
      } 
      throw ex; 
     } finally { 
      if (em != null) { 
       em.close(); 
      } 
     } 
    } 

    public void edit(TbUsuarios tbUsuarios) throws NonexistentEntityException, Exception { 
     EntityManager em = null; 
     try { 
      em = getEntityManager(); 
      em.getTransaction().begin(); 
      tbUsuarios = em.merge(tbUsuarios); 
      em.getTransaction().commit(); 
     } catch (Exception ex) { 
      String msg = ex.getLocalizedMessage(); 
      if (msg == null || msg.length() == 0) { 
       String id = tbUsuarios.getUserName(); 
       if (getTbUsuariosById(id) == null) { 
        throw new NonexistentEntityException("The tbUsuarios with id " + id + " no longer exists."); 
       } 
      } 
      throw ex; 
     } finally { 
      if (em != null) { 
       em.close(); 
      } 
     } 
    } 

    public void delete(String id) throws NonexistentEntityException { 
     EntityManager em = null; 
     try { 
      em = getEntityManager(); 
      em.getTransaction().begin(); 
      TbUsuarios tbUsuarios; 
      try { 
       tbUsuarios = em.getReference(TbUsuarios.class, id); 
       tbUsuarios.getUserName(); 
      } catch (EntityNotFoundException enfe) { 
       throw new NonexistentEntityException("The tbUsuarios with id " + id + " no longer exists.", enfe); 
      } 
      em.remove(tbUsuarios); 
      em.getTransaction().commit(); 
     } finally { 
      if (em != null) { 
       em.close(); 
      } 
     } 
    } 

    public List<TbUsuarios> getAllTbUsuariosEntities() { 
     return getAllTbUsuariosEntities(true, -1, -1); 
    } 

    public List<TbUsuarios> getAllTbUsuariosEntities(int maxResults, int firstResult) { 
     return getAllTbUsuariosEntities(false, maxResults, firstResult); 
    } 

    private List<TbUsuarios> getAllTbUsuariosEntities(boolean all, int maxResults, int firstResult) { 
     EntityManager em = getEntityManager(); 
     try { 
      CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); 
      cq.select(cq.from(TbUsuarios.class)); 
      Query q = em.createQuery(cq); 
      if (!all) { 
       q.setMaxResults(maxResults); 
       q.setFirstResult(firstResult); 
      } 
      return q.getResultList(); 
     } finally { 
      em.close(); 
     } 
    } 

    public TbUsuarios getTbUsuariosById(String id) { 
     EntityManager em = getEntityManager(); 
     try { 
      return em.find(TbUsuarios.class, id); 
     } finally { 
      em.close(); 
     } 
    } 

    public int getTbUsuariosCount() { 
     EntityManager em = getEntityManager(); 
     try { 
      CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); 
      Root<TbUsuarios> rt = cq.from(TbUsuarios.class); 
      cq.select(em.getCriteriaBuilder().count(rt)); 
      Query q = em.createQuery(cq); 
      return ((Long) q.getSingleResult()).intValue(); 
     } finally { 
      em.close(); 
     } 
    } 

    public List<TbUsuarios> searchTbUsuarios(TbUsuarios usuario) 
    { 
     EntityManager em = getEntityManager(); 
     try { 
      CriteriaBuilder cb = em.getCriteriaBuilder(); 
      CriteriaQuery cq = cb.createQuery(TbUsuarios.class); 
      Root<TbUsuarios> p = cq.from(TbUsuarios.class); 

      //Lista de parametros 
      List<Predicate> parametros = new ArrayList<>(); 
      if((usuario.getUserName() != null) && (!usuario.getUserName().trim().equals(""))) 
      { 
       List<TbUsuarios> lst = new ArrayList<>(); 
       lst.add(getTbUsuariosById(usuario.getUserName())); 
       return lst; 
      } 

      if((usuario.getNome() != null) && (!usuario.getNome().trim().equals(""))) 
       parametros.add(cb.like(p.<String>get("nome"), "%" + usuario.getNome() + "%")); 

      if(usuario.getDataCadastro() != null) 
       parametros.add(cb.greaterThanOrEqualTo(p.<Date>get("dataCadastro"), usuario.getDataCadastro())); 

      if((usuario.getEmail() != null) && (!usuario.getEmail().trim().equals(""))) 
       parametros.add(cb.equal(p.<String>get("email"), usuario.getEmail())); 

      //query itself 
      cq.select(p).where(parametros.toArray(new Predicate[0])); 
      //cq.select(p).where(cb.like(p.<String>get("nome"), "%" + usuario.getNome() + "%")); 

      //execute query and do something with result 
      return em.createQuery(cq).getResultList(); 
     } finally { 
      em.close(); 
     }   
    } 
} 

這兩個類是由netbeans生成,並在控制器類中添加了帶有參數的構造函數。

原始控制器類只有一個構造函數接收EntityManagerFactory作爲參數,以隔離有關數據庫操作的知識,我創建了另一個構造函數.EntityManageFactory原始控制器類只有一個構造函數接收EntityManagerFactory作爲參數,以隔離關於數據庫操作的知識,我創建了另一個創建EntityManageFactory的構造函數。

我曾嘗試使用我的控制器是這樣的:

@PersistenceContext(unitName="xxxxx") 
EntityManager em; 

但是EM變量總是空....

什麼是正確的方法是什麼?

回答

1

正如你在談論控制器時,我假設你正在運行一些J2EE應用程序,基於這個應用程序是在支持J2EE的一些應用程序容器中執行的。

我認爲處理或支持您的需求的最佳方式是創建一個控制器類,在需要時調用服務層和此服務層檢索數據時使用DAO類或有時稱爲存儲庫類。

現在如何爲這些實例注入EntityManager,我認爲您應該閱讀一些關於容器管理實體管理器,它們允許您通過依賴注入或JNDI獲得對EM的引用。您可以在您的DAO類中使用@PersistenceContext,這將讓容器管理持久性上下文生命週期併爲您提供一個可用於獲取數據的EntityManager實例。

在控制器中使用@PersistenceContext我不認爲這是思考應用程序中架構和圖層的好方法。當你使用Containers更好地讓他們管理生命週期時,所以使用EnityManagerFactory讓你以一種名爲應用管理的EM的方式對EM負責。

我的建議是做出這樣的事情。

public class UserDAO{ 
    @PersistenceContext 
    private EntityManager em; 
} 
+0

你的建議是我的解決方案的想法(我的問題的最後一段) – user1352652

+0

不工作。我試過@PersistenceContext(nameUnit =「namepersistence」),我的EntityManager變量總是爲空。 – user1352652

+0

您是否在META-INF中有persistence.xml文件,您是否有供您選擇的提供程序的jar文件?你需要有一些配置和jar文件來使這個工作不僅僅是類 – Koitoer