7
respostas

Versão do mysql incompatível

Estou usando a versão do MySQL 8 acredito que seja isso que esteja dando problema na hora de criar as telas no banco de dados

mar. 05, 2021 9:43:10 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
mar. 05, 2021 9:43:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.8.Final}
mar. 05, 2021 9:43:10 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
mar. 05, 2021 9:43:10 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
mar. 05, 2021 9:43:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
mar. 05, 2021 9:43:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
mar. 05, 2021 9:43:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: true
mar. 05, 2021 9:43:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/livrariadb]
mar. 05, 2021 9:43:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {autocommit=true, release_mode=auto, user=root}
mar. 05, 2021 9:43:10 PM org.hibernate.engine.jdbc.internal.JdbcServicesImpl configure
WARN: HHH000342: Could not obtain connection to query metadata : java.lang.ClassCastException: class java.math.BigInteger cannot be cast to class java.lang.Long (java.math.BigInteger and java.lang.Long are in module java.base of loader 'bootstrap')
mar. 05, 2021 9:43:10 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
mar. 05, 2021 9:43:10 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000422: Disabling contextual LOB creation as connection was null
mar. 05, 2021 9:43:10 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
mar. 05, 2021 9:43:10 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Exception in thread "main" java.lang.ExceptionInInitializerError
    at br.com.caelum.livraria.dao.PopulaBanco.main(PopulaBanco.java:17)
7 respostas

Não entendi qual a sua duvida JOELLYTTON

Estou tentando executa a classe PopulaBanco e da o erro abaixo

mar. 08, 2021 1:11:12 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
mar. 08, 2021 1:11:12 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.8.Final}
mar. 08, 2021 1:11:12 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
mar. 08, 2021 1:11:12 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
mar. 08, 2021 1:11:13 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
mar. 08, 2021 1:11:13 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
mar. 08, 2021 1:11:13 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: true
mar. 08, 2021 1:11:13 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/livrariadb]
mar. 08, 2021 1:11:13 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {autocommit=true, release_mode=auto, user=root}
mar. 08, 2021 1:11:13 PM org.hibernate.engine.jdbc.internal.JdbcServicesImpl configure
WARN: HHH000342: Could not obtain connection to query metadata : java.lang.ClassCastException: class java.math.BigInteger cannot be cast to class java.lang.Long (java.math.BigInteger and java.lang.Long are in module java.base of loader 'bootstrap')
mar. 08, 2021 1:11:13 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
mar. 08, 2021 1:11:13 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000422: Disabling contextual LOB creation as connection was null
mar. 08, 2021 1:11:13 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
mar. 08, 2021 1:11:13 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Exception in thread "main" java.lang.ExceptionInInitializerError
    at br.com.caelum.livraria.dao.PopulaBanco.main(PopulaBanco.java:17)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: livraria] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
    at br.com.caelum.livraria.dao.JPAUtil.<clinit>(JPAUtil.java:10)
    ... 1 more

Olá JOELLYTTON,

Preciso que poste os códigos do seu hibernate (persistence.xml), da sua classe DAO, preciso que me informe se o banco de dados foi criado (acredito que seja esse "livrariadb" ) e informe de qual modulo/curso você está tomando como referência este projeto.

Att,

Anderson

Estou fazendo o curso Java e JSF I: Sua aplicação web com JSF2

Modulo

  1. Entendendo MVC e integrando o banco de dados com JPA 2

Código persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
    version="2.0">

    <persistence-unit name="livraria" transaction-type="RESOURCE_LOCAL">

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

        <class>br.com.caelum.livraria.modelo.Livro</class>
        <class>br.com.caelum.livraria.modelo.Autor</class>

        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/livrariadb" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="" />

            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
        </properties>
    </persistence-unit>

</persistence>

Classe Dao

package br.com.caelum.livraria.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;

public class DAO<T> {

    private final Class<T> classe;

    public DAO(Class<T> classe) {
        this.classe = classe;
    }

    public void adiciona(T t) {

        // consegue a entity manager
        EntityManager em = new JPAUtil().getEntityManager();

        // abre transacao
        em.getTransaction().begin();

        // persiste o objeto
        em.persist(t);

        // commita a transacao
        em.getTransaction().commit();

        // fecha a entity manager
        em.close();
    }

    public void remove(T t) {
        EntityManager em = new JPAUtil().getEntityManager();
        em.getTransaction().begin();

        em.remove(em.merge(t));

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

    public void atualiza(T t) {
        EntityManager em = new JPAUtil().getEntityManager();
        em.getTransaction().begin();

        em.merge(t);

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

    public List<T> listaTodos() {
        EntityManager em = new JPAUtil().getEntityManager();
        CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
        query.select(query.from(classe));

        List<T> lista = em.createQuery(query).getResultList();

        em.close();
        return lista;
    }

    public T buscaPorId(Integer id) {
        EntityManager em = new JPAUtil().getEntityManager();
        T instancia = em.find(classe, id);
        em.close();
        return instancia;
    }

    public int contaTodos() {
        EntityManager em = new JPAUtil().getEntityManager();
        long result = (Long) em.createQuery("select count(n) from livro n")
                .getSingleResult();
        em.close();

        return (int) result;
    }

    public List<T> listaTodosPaginada(int firstResult, int maxResults) {
        EntityManager em = new JPAUtil().getEntityManager();
        CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
        query.select(query.from(classe));

        List<T> lista = em.createQuery(query).setFirstResult(firstResult)
                .setMaxResults(maxResults).getResultList();

        em.close();
        return lista;
    }

}

Classe JPAUtil

package br.com.caelum.livraria.dao;

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

public class JPAUtil {

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

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

    public void close(EntityManager em) {
        em.close();
    }
}

Dao PopulaBanco

package br.com.caelum.livraria.dao;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.persistence.EntityManager;

import br.com.caelum.livraria.modelo.Autor;
import br.com.caelum.livraria.modelo.Livro;

public class PopulaBanco {

    public static void main(String[] args) {

        EntityManager em = new JPAUtil().getEntityManager();

        em.getTransaction().begin();

        Autor assis = geraAutor("Machado de Assis");
        em.persist(assis);

        Autor amado = geraAutor("Jorge Amado");
        em.persist(amado);

        Autor coelho = geraAutor("Paulo Coelho");
        em.persist(coelho);

        Livro casmurro = geraLivro("978-8-52-504464-8", "Dom Casmurro",
                "10/01/1899", 24.90, assis);
        Livro memorias = geraLivro("978-8-50-815415-9",
                "Memorias Postumas de Bras Cubas", "01/01/1881", 19.90, assis);
        Livro quincas = geraLivro("978-8-50-804084-1", "Quincas Borba",
                "01/01/1891", 16.90, assis);

        em.persist(casmurro);
        em.persist(memorias);
        em.persist(quincas);

        Livro alquemista = geraLivro("978-8-57-542758-3", "O Alquimista",
                "01/01/1988", 19.90, coelho);
        Livro brida = geraLivro("978-8-50-567258-7", "Brida", "01/01/1990",
                12.90, coelho);
        Livro valkirias = geraLivro("978-8-52-812458-8", "As Valkirias",
                "01/01/1992", 29.90, coelho);
        Livro maao = geraLivro("978-8-51-892238-9", "O Diario de um Mago",
                "01/01/1987", 9.90, coelho);

        em.persist(alquemista);
        em.persist(brida);
        em.persist(valkirias);
        em.persist(maao);

        Livro capitaes = geraLivro("978-8-50-831169-1", "Capitaes da Areia",
                "01/01/1937", 6.90, amado);
        Livro flor = geraLivro("978-8-53-592569-9",
                "Dona Flor e Seus Dois Maridos", "01/01/1966", 18.90, amado);

        em.persist(capitaes);
        em.persist(flor);

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

    }

    private static Autor geraAutor(String nome) {
        Autor autor = new Autor();
        autor.setNome(nome);
        return autor;
    }

    private static Livro geraLivro(String isbn, String titulo, String data,
            double preco, Autor autor) {
        Livro livro = new Livro();
        livro.setIsbn(isbn);
        livro.setTitulo(titulo);
        livro.setDataLancamento(data);
        livro.setPreco(preco);
        livro.adicionaAutor(autor);
        return livro;
    }

    @SuppressWarnings("unused")
    private static Calendar parseData(String data) {
        try {
            Date date = new SimpleDateFormat("dd/MM/yyyy").parse(data);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar;
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

}