gpt4 book ai didi

java - 具有依赖注入(inject)的 JPA Controller

转载 作者:行者123 更新时间:2023-12-01 13:12:43 25 4
gpt4 key购买 nike

我有以下类(class)......

数据库实体bean

@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 + " ]";
}

}

还有一个 Controller 类(如 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生成的,在 Controller 类中我添加了不带参数的构造函数。

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

我尝试在我的 Controller 中使用这样的东西:

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

但 em 变量始终为 null....

正确的做法是什么?

最佳答案

当您谈论 Controller 时,我假设您正在运行一些 J2EE 应用程序,因为该应用程序是在支持 J2EE 的一些应用程序容器中执行的。

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

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

在 Controller 中使用@PersistenceContext 我认为这不是思考应用程序中的架构和层的好方法。当您使用容器时,最好让它们管理生命周期,因此使用 EnityManagerFactory 可以让您以一种名为应用程序管理的 EM 的方式对 EM 负责。

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

public class UserDAO{
@PersistenceContext
private EntityManager em;
}

关于java - 具有依赖注入(inject)的 JPA Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22726451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com