When creating EntityManagerFactory with the Persistence unit the program stops JAVA

1

I have a problem with my web application that I am developing using JPA, which worked fine until yesterday.
With the help of Java DEBUG I have executed line by line and I noticed that the problem is sometimes in the EntityManagerFactory , and other times in the JPA controller of the entity when going through the method getEntityManager(). Al To say problem I mean that simply after executing that line of code does not advance to the next one, the program simply does not do anything.

I do not know why this happens. Here is my JPA controller, believe it with the assistant that brings netbeans.

The method I use is findEmpresaEntities()

public class UsuarioJpaController implements Serializable {

public UsuarioJpaController(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(Usuario usuario) throws RollbackFailureException, Exception {
    EntityManager em = null;
    try {
        utx.begin();
        em = getEntityManager();
        em.persist(usuario);
        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(Usuario usuario) throws NonexistentEntityException, RollbackFailureException, Exception {
    EntityManager em = null;
    try {
        utx.begin();
        em = getEntityManager();
        usuario = em.merge(usuario);
        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 = usuario.getIdusuario();
            if (findUsuario(id) == null) {
                throw new NonexistentEntityException("The usuario 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();
        Usuario usuario;
        try {
            usuario = em.getReference(Usuario.class, id);
            usuario.getIdusuario();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The usuario with id " + id + " no longer exists.", enfe);
        }
        em.remove(usuario);
        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<Usuario> findUsuarioEntities() {
    return findUsuarioEntities(true, -1, -1);
}

public List<Usuario> findUsuarioEntities(int maxResults, int firstResult) {
    return findUsuarioEntities(false, maxResults, firstResult);
}

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

public Usuario findUsuario(Integer id) {
    EntityManager em = getEntityManager();
    try {
        return em.find(Usuario.class, id);
    } finally {
        em.close();
    }
}

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

}

This class is where I create the EMF

public class BusinessProcedure {

public static boolean validateUser(UsuarioTO miUsuario){

    boolean flag = false;

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("ControlAdministrativoPU");

    UsuarioJpaController usuarioDAO = new UsuarioJpaController(null,emf);

    List<Usuario> lista = usuarioDAO.findUsuarioEntities();

    for (Usuario u :lista) {

                if(miUsuario.getRfc().equals(u.getRfc()) && miUsuario.getPass().equals(u.getPass()) && miUsuario.getUsuario().equals(u.getUsuario()) ) {flag = true; break;}
                else flag = false;

            }

    emf.close();

    return flag;

}

Here is Persitence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="ControlAdministrativoPU" transaction-type="JTA">
    <jta-data-source>java:app/MySQLControl</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
  </persistence-unit>
</persistence>

Someone will know how to solve this, some recommendations?

Thanks

    
asked by Salvador Mendez 11.07.2017 в 17:00
source

1 answer

1

Hi, I recommend that you do not use the Netbeans helper at all, now if you use it, it's a lot of garbage, what I do is remove all that garbage I do not use, for example the UserTransaction.

The creation and execution of the EntityManagerFactory and EntityManager, must be done in the business layer always, there is a more convenient way to implement it and create it which is:

@PersistenceContext(unitName = "ColegioPU")
private EntityManager em;

But I leave you the example, with the creation of a course and the list of them, using the assistant of Netbeans so that you are familiar with it.

public class CursoJpaController implements Serializable {


public CursoJpaController() {
    emf = Persistence.createEntityManagerFactory("ColegioPU");
}

private EntityManagerFactory emf = null;

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

public Curso registrar(Curso curso) throws Exception{
    EntityManager em = null;
    Curso cur = new Curso();
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        em.persist(curso);
        cur = em.merge(curso);
        em.getTransaction().commit();
    }catch (Exception e) {
        System.out.println("creates: "+ e.getMessage());
    }finally {
        if (em != null) {
            em.close();
        }
    }
    return cur;
}
public List<Curso> findCursoEntities() {
    return findCursoEntities(true, -1, -1);
}

public List<Curso> findCursoEntities(int maxResults, int firstResult) {
    return findCursoEntities(false, maxResults, firstResult);
}

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

public Curso findCurso(Integer id) {
    EntityManager em = getEntityManager();
    try {
        return em.find(Curso.class, id);
    } finally {
        em.close();
    }
}

}

For the persistence you must always include the entities mapped from the database, additional the connection pool if you are not doing the same by JDNI (configuring it from the application server), then you must indicate all the connection parameters, I leave you an example:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ColegioPU" transaction-type="JTA">
    <jta-data-source>java:app/Prog2</jta-data-source>
    <class>com.colegio.co.entities.Alumno</class>
    <class>com.colegio.co.entities.Curso</class>
    <class>com.colegio.co.entities.Tipos</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>

    <properties>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/colegio"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value="1234"/>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="eclipselink.logging.level" value="FINE"/>
    </properties>
</persistence-unit>

If you do not understand something, just ask, since it's free :).

    
answered by 12.07.2017 в 19:06