Reputation: 425
I have the follow classes....
Database 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 + " ]";
}
}
And one controller class (like 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();
}
}
}
The two classes were generated by netbeans, and in the controller class I have added the contructor withou parameters.
The original controller classe have just one constructor that receive a EntityManagerFactory as parameter, to isolate koowledge about database operations, I have created the other constructor.EntityManageFactoryThe original controller classe have just one constructor that receive a EntityManagerFactory as parameter, to isolate knowledge about database operations, I have created the other constructor that create a EntityManageFactory.
I have tried use in my controller something like this:
@PersistenceContext(unitName="xxxxx")
EntityManager em;
But em variable always null....
What is the correct way?
Upvotes: 0
Views: 831
Reputation: 19533
As you are talking about controller I assume you are running some J2EE application, based on that this applications are executed in the some application container that support J2EE.
I think the best way to handle or support your requirements is create a controller class that call a service layer and this service layer when required retrieve data use a DAO class or sometimes called repository class.
Now how to inject the EntityManager to those instances, I think you should read something about Container-Managed Entity Manager, that allow you to obtain reference to the EM through dependcy injection or JNDI. You could use @PersistenceContext
in your DAO classes this will let the container manage the persistence context lifecycle and give you an EntityManager instance that you can use to obtain data.
Use @PersistenceContext
in the Controllers I don't think is a good way thinking in the architecture and layers in an application. When you use Containers is better to let them managed the lifecycle, so using EnityManagerFactory makes your responsible for the EM in a way named Application-Managed EM.
My suggestion is make something like this.
public class UserDAO{
@PersistenceContext
private EntityManager em;
}
Upvotes: 1