Problems opening connection to JSF and JPA

Asked

Viewed 470 times

3

There’s something wrong with mine persistence.xml? I can’t open the connection.

My Bean is like this:

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.casadocodigo.jsfjpa.entities.Automovel;
import br.com.casadocodigo.jsfjpa.persistence.JPAUtil;

@ManagedBean
public class AutomovelBean {

    private Automovel automovel = new Automovel();

    private List<Automovel> automoveis;


    public Automovel getAutomovel() {
        return automovel;
    }   

    public void setAutomovel(Automovel automovel) {
        this.automovel = automovel;
    }

    public void salva(Automovel automovel) {

        EntityManager em = JPAUtil.getEntityManager();
        em.getTransaction().begin();

        em.persist(automovel);

        em.getTransaction().commit();
        em.close();

        System.out.println("Marca: " + automovel.getMarca());
    }

    public List<Automovel> getAutomoveis() {

        EntityManager em = JPAUtil.getEntityManager();

        Query q = em.createQuery("select a from Automovel a", Automovel.class);

        this.automoveis = q.getResultList();
        em.close();
        return automoveis;
    }

}

Jpautil:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtil {

    private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");

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

Xhtml file:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">

    <h:head>
        <title>Cadastro de Automoveis</title>
    </h:head>

    <h:body>
        <h:form>
            <h:panelGrid columns="2">

                Marca: <h:inputText value="#{automovelBean.automovel.marca}" /><br/>

                Modelo: <h:inputText value="#{automovelBean.automovel.modelo}"/><br/>

                Ano de Fabricacão: <h:inputText value="#{automovelBean.automovel.anoFabricacao}"/><br/>

                Ano do Modelo: <h:inputText value="#{automovelBean.automovel.anoModelo}"/><br/>

                Observações: <h:inputTextarea value="#{automovelBean.automovel.observacoes}"/><br/>

                <h:commandButton value="Salvar" action="#{automovelBean.salva(automovelBean.automovel)}" />
            </h:panelGrid>
        </h:form>
    </h:body>
</html>

And the persistence:

<?xml version="1.0" encoding="UTF-8"?>

<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="default">
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/automoveis" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="root" />

            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create" />

            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />

        </properties>
    </persistence-unit>
</persistence>

The mistake that is happening:

HTTP Status 500 - javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection

type: Exception report

message: javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection

description: The server encountered an internal error that prevented it from fulfilling this request.

exception: 

javax.servlet.ServletException: javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
  • Dude, you added the connection driver to your lib? in addition, you must declare your entities to the persistence.xml

2 answers

1

There are really some problems with your file persistence.xml, but it is unclear whether the problem is specifically in persistence.xml.

  • Make sure everything is ok with your Mysql Connection Driver;

    • Check that the database you created is with the same name stated in your persistence.xml
    • In his persistence.xml is missing the declaration of its entities which will be tables in the database. vc will have to add the Fully
      Qualified name
      within the tags <class></class>, be careful with the hierarchy of tags;
    • Add the declaration of the JPA Hibernate provider (relative to the version of the file persistence.xml which is 2.0);

    <provider>org.hibernate.ejb.HibernatePersistence</provider>

    • withdraw the static of his method getEntityManager() in the Jpautil class.
  • I was able to fix the problem. Mysql was not installed.

  • @Gabrielfaria, believe me. Now all that remains is to close the question. :)

0

Try to add the following to your persistence.xml:

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

Add that before the <properties>.

Also, if that doesn’t resolve, then post your full stacktrace so we can help you better. I say this because the stacktrace does not seem to be complete. Please put it in full so that we can help you. Clearly it is a problem in connection with the database, but with incomplete stacktrace you cannot know exactly which.

Also, I note that your architecture has a problem for allowing access to entity Beans after the EntityManager have been closed and allow them to be handled directly by the JSF. This won’t necessarily make your code crash or have some kind of serious bug, but it’s a fragile architecture where it’s very easy to do something wrong. The reason is that some properties may be Lazy, and when accessing them in JSF after the closure of EntityManager you will take a org.hibernate.LazyInitializationException. To avoid having to control this in detail, which is quite boring and very prone to silly errors, I recommend you use a bean class to talk to JSF and a different bean class (the entity bean) to talk to Hibernate/JPA, and in the Managed bean you do something that converts one into another without ever letting the entity bean be referenced after the EntityManager have been closed. Also, with this approach, you also decouple the structure of the visualization pages from the object/relational database mapping structure.

Another problem is that if your business methods fail with any exception after the EntityManager have been created, it will not be closed and will be orphaned. To avoid this, close the EntityManager in blocks finally.

Finally, replace this:

Query q = em.createQuery("select a from Automovel a", Automovel.class);

That’s why:

TypedQuery<Automovel> q = em.createQuery("select a from Automovel a", Automovel.class);
  • Thanks for your help Victor. I’m studying with a book and I’m at the beginning. in the book github there are these changes from "Query q", to "Typedquery<Automovel>", however, as I am at the beginning the author is showing step by step. I added before the <properties> the <Provider> you sent, but it didn’t work, I will post the full stacktrace. thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.