Solucionado (ver solução)
Solucionado
(ver solução)
12
respostas

Como utilizar a versão mais recente do Hibernate?

Ao tentar utilizar a versão 5.2.0 do Hibernate recebo a seguinte Exception: No Persistence provider for EntityManager named financas.

Quando uso as bibliotecas passadas no zip do projeto, funciona perfeitamente, sem alterar nada em nenhum código. O que mudou com a nova versão?

12 respostas

olá Carlos,

  • Como que está e onde está o seu persistence.xml?
  • Verifique se o nome do seu persistence-unit dentro do persistence.xml está correto. -Verifique se todas as libs do hibernate foram baixadas.

Está no /src/META-INF

Não tem nada errado com o arquivo, pois funciona sem alteração nenhuma, quando utilizo as libs do Hibernate 4.x, que é utilizado no curso.

Ao mudar a versão das libs que recebo o erro.

Estou passando pelo mesmo problema do Carlos Vinicius... Ao adicionar as bibliotecas do hibernate 5.2 recebo o Exception: No Persistence provider for EntityManager named financas.

Quando uso o a versão 4.3 o projeto funciona normal.

Até o momento não consegui usar a versão 5.2 do hibernate...

Olá, Carlos e Maurício!

Tentem utilizar o seguinte provider dentro de persistence-unit no arquivo persistence.xml:

org.hibernate.jpa.HibernatePersistenceProvider

Alterei mas o erro continua:

jun 26, 2016 6:44:05 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: financas
    ...]
jun 26, 2016 6:44:06 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.0.Final}
jun 26, 2016 6:44:06 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
jun 26, 2016 6:44:06 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
jun 26, 2016 6:44:06 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
jun 26, 2016 6:44:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
jun 26, 2016 6:44:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/financas]
jun 26, 2016 6:44:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
jun 26, 2016 6:44:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
jun 26, 2016 6:44:06 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
jun 26, 2016 6:44:06 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
jun 26, 2016 6:44:07 PM org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl processGetTableResults
INFO: HHH000262: Table not found: Conta
Exception in thread "main" java.lang.ExceptionInInitializerError
    at financas.teste.TesteMovimentacaoConta.main(TesteMovimentacaoConta.java:11)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: financas] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:961)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:891)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at financas.util.JPAUtil.<clinit>(JPAUtil.java:11)
    ... 1 more
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Attempt to resolve foreign key metadata from JDBC metadata failed to find column mappings for foreign key named [FK257EB923D865A8A3]
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl$ForeignKeyBuilderImpl.build(InformationExtractorJdbcDatabaseMetaDataImpl.java:727)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl$ForeignKeyBuilderImpl.build(InformationExtractorJdbcDatabaseMetaDataImpl.java:708)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getForeignKeys(InformationExtractorJdbcDatabaseMetaDataImpl.java:691)
    at org.hibernate.tool.schema.extract.internal.TableInformationImpl.foreignKeys(TableInformationImpl.java:88)
    at org.hibernate.tool.schema.extract.internal.TableInformationImpl.getForeignKey(TableInformationImpl.java:99)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.findMatchingForeignKey(SchemaMigratorImpl.java:530)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:506)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.performMigration(SchemaMigratorImpl.java:315)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:137)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:110)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:176)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:308)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:476)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:888)
    ... 5 more

Main que rodei:

package financas.teste;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import financas.util.JPAUtil;

public class TesteMovimentacaoConta {

    public static void main(String[] args) {
        EntityManager manager = new JPAUtil().getEntityManager();

        TypedQuery<Long> query = manager.createQuery("SELECT COUNT(m) FROM Movimentacao m", Long.class);

        System.out.println(query.getSingleResult());

        manager.close();
    }

}

JPAUtil:

package financas.util;

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

public class JPAUtil {

    private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("financas");

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

Algo errado?

Esqueci de compartilhar o persistence.xml:

<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">

    <!-- unidade de persistencia com o nome financas -->
    <persistence-unit name="financas">

        <!-- Implementação do JPA, no nosso caso Hibernate -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <!-- Aqui são listadas todas as entidades -->
        <class>financas.modelo.Conta</class>
        <class>financas.modelo.Movimentacao</class>

        <properties>
            <!-- Propriedades JDBC -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/financas" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="senha" />

            <!-- Configurações específicas do Hibernate -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <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>

Oi Carlos,

Nas suas entidades Conta e Movimentacao tem como garantir IDENTITY como estratégia de geração da chave primaria?

Algo assim:

@Entity
public class Conta {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

   //outros atributos omitidos

A mesma coisa na classe Movimentacao.

Tbm garante que não há nenhuma tabela criada e apague elas no banco.

Abs, Nico

Ola Mateus e Nico! As dicas funcionaram, agora estou conseguindo usar a ver 5.2 do hibernate, era o provider mesmo.

Obrigado.

Até.

Com a alteração sugerida pelo Nico consigo rodar PopulaConta OU PopulaMovimentacao.

Não consigo rodar as duas. Se rodo a PopulaConta, e depois tento rodar PopulaMovimentacao, recebo o erro:

jun 29, 2016 9:52:10 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: financas
    ...]
jun 29, 2016 9:52:10 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.0.Final}
jun 29, 2016 9:52:10 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
jun 29, 2016 9:52:10 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
jun 29, 2016 9:52:10 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
jun 29, 2016 9:52:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
jun 29, 2016 9:52:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/financas]
jun 29, 2016 9:52:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
jun 29, 2016 9:52:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
jun 29, 2016 9:52:10 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
jun 29, 2016 9:52:10 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
jun 29, 2016 9:52:11 AM org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl processGetTableResults
INFO: HHH000262: Table not found: Conta
Exception in thread "main" java.lang.ExceptionInInitializerError
    at financas.util.PopulaConta.main(PopulaConta.java:11)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: financas] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:961)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:891)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at financas.util.JPAUtil.<clinit>(JPAUtil.java:9)
    ... 1 more
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Attempt to resolve foreign key metadata from JDBC metadata failed to find column mappings for foreign key named [FKthcy44mjtg87orpl9a3nfso7b]
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl$ForeignKeyBuilderImpl.build(InformationExtractorJdbcDatabaseMetaDataImpl.java:727)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl$ForeignKeyBuilderImpl.build(InformationExtractorJdbcDatabaseMetaDataImpl.java:708)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getForeignKeys(InformationExtractorJdbcDatabaseMetaDataImpl.java:691)
    at org.hibernate.tool.schema.extract.internal.TableInformationImpl.foreignKeys(TableInformationImpl.java:88)
    at org.hibernate.tool.schema.extract.internal.TableInformationImpl.getForeignKey(TableInformationImpl.java:99)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.findMatchingForeignKey(SchemaMigratorImpl.java:530)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:506)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.performMigration(SchemaMigratorImpl.java:315)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:137)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:110)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:176)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:308)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:476)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:888)
    ... 5 more

Segue todo meu projeto: https://mega.nz/#!WFRACLrY!kduhxw_JU--UM5yash3TcoXxSZnzKihlLP3KhA2l9d8

solução!

Oi Carlos,

isso é um bug do Hibernate (fogo!!), introduzido na versao 5.2:

https://hibernate.atlassian.net/browse/HHH-10802

Aconselho usar as bibliotecas do curso, essas foram testados.

abs

instalei o Wildfly 10, que ja vem com as bibliotecas nativas, quando inicio o servidor tudo roda perfeitamente, porem ao testa-lo com o arquivo main, recebo a menssagem: "No Persistence provider for EntityManager named ..." - O persistence.xlm esta no lugar certo. podem me majudar?

persistence.xml

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

org.hibernate.jpa.HibernatePersistenceProvider br.com.wolf.modelo.Conta

Conta.java

package br.com.wolf.modelo;

import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator;

@Entity @SequenceGenerator(name = "SEQ_Conta", sequenceName = "SEQ_Conta", initialValue = 1) public class Conta {

@Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_Conta") private Integer idConta; private String emailConta; private String senhaConta;

public Integer getIdConta() { return idConta; }

public String getEmailConta() { return emailConta; }

public void setEmailConta(String emailConta) { this.emailConta = emailConta; }

public String getSenhaConta() { return senhaConta; }

public void setSenhaConta(String senhaConta) { this.senhaConta = senhaConta; }

}

TesteJPA.java

package br.com.wolf.run;

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

import br.com.wolf.modelo.Conta;

public class TesteJPA {

public static void main(String[] args) {

double inicio = System.currentTimeMillis();

EntityManagerFactory emf = Persistence.createEntityManagerFactory("wolfportal"); EntityManager em = emf.createEntityManager();

Conta conta = new Conta(); conta.setEmailConta("teste"); conta.setSenhaConta("123");

em.getTransaction().begin();

em.persist(conta);

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

double fim = System.currentTimeMillis(); System.out.println("Executado em: " + (fim - inicio) / 1000 + "s");

} }

==================

Erro

Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named wolfportal at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39) at br.com.wolf.run.TesteJPA.main(TesteJPA.java:18)

Oi Vagner,

esse post já foi resolvido, tem como criar um novo por favor?

Obrigado, Nico