具有依赖注入的JPA控制器

时间:2014-03-29 03:01:09

标签: java jpa dependency-injection

我有以下课程......

数据库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生成的,在控制器类中我添加了带有参数的构造函数。

原始控制器classe只有一个构造函数接收一个EntityManagerFactory作为参数,以隔离关于数据库操作的知识,我创建了另一个构造函数.EntityManageFactory原始控制器classe只有一个构造函数接收一个EntityManagerFactory作为参数,以隔离知识关于数据库操作,我创建了另一个创建EntityManageFactory的构造函数。

我试过在我的控制器中使用这样的东西:

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

但是em变量总是为null ....

正确的方法是什么?

1 个答案:

答案 0 :(得分:1)

在谈论控制器时,我假设您正在运行一些J2EE应用程序,基于此应用程序在支持J2EE的某个应用程序容器中执行。

我认为处理或支持您的需求的最佳方法是创建一个调用服务层的控制器类,并在需要时使用DAO类或有时称为存储库类检索数据时使用此服务层。

现在如何将EntityManager注入到这些实例中,我认为您应该阅读一些关于容器管理的实体管理器的内容,它允许您通过依赖注入或JNDI获取对EM的引用。您可以在DAO类中使用@PersistenceContext,这将使容器管理持久性上下文生命周期,并为您提供可用于获取数据的EntityManager实例。

在控制器中使用@PersistenceContext我不认为考虑应用程序中的体系结构和层是一种好方法。当您使用容器时,最好让它们管理生命周期,因此使用EnityManagerFactory会以名为应用程序管理的EM 的方式使您负责EM。

我的建议是做这样的事情。

public class UserDAO{
   @PersistenceContext
   private EntityManager em;
}