1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

Erro ao conectar ao mySql - JPA

Amigo, estou com um problema fantasma rsrsr, não estou conseguindo achar a causa raiz do o por que não está conseguindo conectar ao banco.

podem me ajudar, tenho certeza que o erro é bobo mais não estou enxergando.

segue as classes:

JPA:

package br.com.farmacia.JPA;

import java.awt.Component;
import java.awt.Container;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * 
 * @author Familia
 * @param <T>
 */
public class JPAUtilProdCPP<T> {

    @SuppressWarnings("rawtypes")
    private static JPAUtilProdCPP me;
    private EntityManagerFactory emf;

    private JPAUtilProdCPP() {

        try {
            emf = Persistence.createEntityManagerFactory("Estacionamento");

        } catch (Exception e) {

            JOptionPane.showMessageDialog(null,"Houve um erro ao tentar conectar no Banco");
            e.printStackTrace();

        }

    }

    @SuppressWarnings("rawtypes")
    public static JPAUtilProdCPP getInstance() {

        if (me == null) {

            me = new JPAUtilProdCPP();
        }

        return me;
    }

    // Retornando o EntityManager
    public EntityManager getEntityManager() {

        EntityManager toReturn = emf.createEntityManager();
        toReturn.getTransaction().begin();

        return toReturn;
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> List<T> getList(Class<T> classToCast, String jpql,
            Object... parameters) {

        List<T> toReturn = null;
        EntityManager em = getEntityManager();
        Query qr = em.createQuery(jpql);

        for (int i = 0; i < parameters.length; i++) {

            qr.setParameter(i + 1, parameters[i]);
        }

        toReturn = qr.getResultList();
        em.getTransaction().commit();
        em.close();

        return toReturn;
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> T getSqlParam(Class<T> classToCast, String jpql,
            Object... parameters) {

        T toReturn = null;
        EntityManager em = getEntityManager();
        Query qr = em.createQuery(jpql);

        for (int i = 0; i < parameters.length; i++) {

            qr.setParameter(i + 1, parameters[i]);
        }

        toReturn = (T) qr.getSingleResult();
        em.getTransaction().commit();
        em.close();

        return toReturn;
    }

    public Double getTotalSql(String jpql, Object... parameters) {

        EntityManager em = getEntityManager();
        Query qr = em.createQuery(jpql);

        for (int i = 0; i < parameters.length; i++) {

            qr.setParameter(i + 1, parameters[i]);
        }

        Double toReturn;

        try {
            toReturn = (Double) qr.getSingleResult();
        } catch (Exception e) {

            toReturn = 0.0;

        }

        return toReturn;

    }

    public Integer getMax(String jpql, Object... parameters) {

        EntityManager em = getEntityManager();
        Query qr = em.createNativeQuery(jpql);

        for (int i = 0; i < parameters.length; i++) {

            qr.setParameter(i + 1, parameters[i]);
        }

        Integer toReturn = null;

        try {
            toReturn = (Integer) qr.getSingleResult();

        } catch (Exception e) {

            // e.printStackTrace();
            toReturn = null;

        }

        return toReturn;

    }

    public int SQLNativoExec(String jpql, Object... parameters) {

        EntityManager em = getEntityManager();
        Query qr = em.createNativeQuery(jpql);

        for (int i = 0; i < parameters.length; i++) {

            qr.setParameter(i + 1, parameters[i]);
        }

        int toReturn;

        try {
            toReturn = qr.executeUpdate();
            em.getTransaction().commit();
        } catch (Exception e) {

            e.printStackTrace();
            toReturn = 0;

        }

        return toReturn;

    }

    @SuppressWarnings("unchecked")
    public List<T> SQLNativoSelect(String jpql, Object... parameters) {

        EntityManager em = getEntityManager();
        Query qr = em.createNativeQuery(jpql);
        // Query tr = em.createNativeQuery(jpql, getClass());

        for (int i = 0; i < parameters.length; i++) {

            qr.setParameter(i + 1, parameters[i]);
        }

        List<T> toReturn;

        try {
            toReturn = qr.getResultList();
            em.getTransaction().commit();
        } catch (Exception e) {

            e.printStackTrace();
            toReturn = null;

        }

        return toReturn;

    }

    @SuppressWarnings("hiding")
    public <T> T getEntity(Class<T> entityClass, Serializable pk) {

        EntityManager em = getEntityManager();
        T toReturn = em.find(entityClass, pk);
        em.getTransaction().commit();
        em.close();
        // teste dsf

        return toReturn;
    }

    @SuppressWarnings({ "hiding", "unchecked" })
    public <T> T gravaEntity(Class<T> entityClass, Object dados) {

        EntityManager em = getEntityManager();

        em.persist(dados);

        T toReturn = (T) dados;

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

        return toReturn;
    }

    @SuppressWarnings("rawtypes")
    static public void setAtributos(Object objeto, Object Valor) {
        String aux = null;
        Class classe = objeto.getClass();
        Field[] campos = classe.getDeclaredFields();
        for (int i = 0; i < campos.length; i++) {
            aux = "jtf";
            if (campos[i].getName().substring(0, 3).trim().equals(aux)) {
            }
        }
    }

    @SuppressWarnings("unused")
    static public void ideiaVamosVer(String nome) {

        JTextField jt = new JTextField();
        // jt = (JTextField) nome;
    }

    public static void carregaDadosClasse(Container container) {

        Component components[] = container.getComponents();

        for (Component component : components) {

            if (component instanceof javax.swing.JFormattedTextField) {
                JFormattedTextField field = (javax.swing.JFormattedTextField) component;
                field.setValue(null);
            } else if (component instanceof JTextField) {
                JTextField field = (JTextField) component;
                System.out.println("Nome do componente: " + field.getName());

                if (field.getName() == "txtnomeRazao") {

                    JOptionPane.showMessageDialog(null,
                            "Digite um valor válido no campo",
                            "Erro de validação" + field.getText(),
                            JOptionPane.ERROR_MESSAGE);

                }
                field.setText("");
            } else if (component instanceof javax.swing.JTextArea) {
                JTextArea area = (JTextArea) component;
                area.setText("");
            }
            // else if (component instanceof Container) {
            // limparCamposNoContainer((Container) component);
            // }
        }
    }

    public static byte[] gerarHash(String frase, String algoritmo) {

        /*
         * String frase = "Quero gerar códigos hash desta mensagem.";
         * System.out.println(stringHexa(gerarHash(frase, "MD5")));
         * System.out.println(stringHexa(gerarHash(frase, "SHA-1")));
         * System.out.println(stringHexa(gerarHash(frase, "SHA-256")));
         */

        try {
            MessageDigest md = MessageDigest.getInstance(algoritmo);
            md.update(frase.getBytes());
            return md.digest();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static String stringHexa(byte[] bytes) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            int parteAlta = ((bytes[i] >> 4) & 0xf) << 4;
            int parteBaixa = bytes[i] & 0xf;
            if (parteAlta == 0)
                s.append('0');
            s.append(Integer.toHexString(parteAlta | parteBaixa));
        }
        return s.toString();
    }

    public static String getHost() {

        InetAddress thisIp = null;

        try {
            thisIp = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {

            e.printStackTrace();
        }

        return thisIp.getHostAddress();
    }

    /**
     * Converte uma String para um objeto Date. Caso a String seja vazia ou
     * nula, retorna null - para facilitar em casos onde formulários podem ter
     * campos de datas vazios.
     * 
     * @param data
     *            String no formato dd/MM/yyyy a ser formatada
     * @return Date Objeto Date ou null caso receba uma String vazia ou nula
     * @throws Exception
     *             Caso a String esteja no formato errado
     */
    public static Date formataData(String data) throws Exception {
        if (data == null || data.equals("")
                || data.equals("00/00/0000 00:00:00"))
            return null;

        Date date = null;
        try {
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            date = (java.util.Date) formatter.parse(data);
        } catch (ParseException e) {
            throw e;
        }
        return date;
    }

}

persistence

<persistence version="1.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_1_0.xsd">
    <persistence-unit name="Estacionamento"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
            <class>br.com.estacionamento.mapeamento.Carro</class>
            <class>br.com.estacionamento.mapeamento.Cliente</class>
            <class>br.com.estacionamento.mapeamento.Usuario</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/estacionamento" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="12345" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
        </properties>

    </persistence-unit>

</persistence>

ERRO:

javax.persistence.PersistenceException: No Persistence provider for EntityManager named Estacionamento
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
    at br.com.farmacia.JPA.JPAUtilProdCPP.<init>(JPAUtilProdCPP.java:40)
    at br.com.farmacia.JPA.JPAUtilProdCPP.getInstance(JPAUtilProdCPP.java:56)
    at br.com.farmacia.controller.Controle.<init>(Controle.java:29)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(Unknown Source)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(Unknown Source)
    at javafx.fxml.FXMLLoader$Element.processStartElement(Unknown Source)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(Unknown Source)
    at javafx.fxml.FXMLLoader.processStartElement(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.load(Unknown Source)
    at br.com.farmacia.principal.Main.start(Main.java:20)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(Unknown Source)
    at com.sun.javafx.application.LauncherImpl$$Lambda$51/988183337.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$$Lambda$45/1051754451.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null$164(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$$Lambda$47/356002977.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$$Lambda$46/1775282465.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$141(Unknown Source)
    at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$147(Unknown Source)
    at com.sun.javafx.application.LauncherImpl$$Lambda$48/1732398722.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: javafx.fxml.LoadException: 
/D:/DOUGLAS/workpace_javaFx/Farmacia/bin/br/com/farmacia/css/Tela.fxml:12

    at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.load(Unknown Source)
    at br.com.farmacia.principal.Main.start(Main.java:20)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(Unknown Source)
    at com.sun.javafx.application.LauncherImpl$$Lambda$51/988183337.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$$Lambda$45/1051754451.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null$164(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$$Lambda$47/356002977.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$$Lambda$46/1775282465.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$141(Unknown Source)
    at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
    ... 1 more
Caused by: java.lang.NullPointerException
    at br.com.farmacia.JPA.JPAUtilProdCPP.getEntityManager(JPAUtilProdCPP.java:65)
    at br.com.farmacia.controller.Controle.<init>(Controle.java:29)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(Unknown Source)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(Unknown Source)
    at javafx.fxml.FXMLLoader$Element.processStartElement(Unknown Source)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(Unknown Source)
    at javafx.fxml.FXMLLoader.processStartElement(Unknown Source)
    ... 23 more
Exception running application br.com.farmacia.principal.Main

agradeço.

  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

1 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags jpa java javafx estrutura-de-dados ou faça a sua própria pergunta.