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

Exception in thread "main" java.lang.IllegalStateException: Transaction not successfully started

Cria a tabela mas nao insere:

 Hibernate: 

    create table Conta (
       id integer not null auto_increment,
        agencia varchar(255),
        banco varchar(255),
        numero varchar(255),
        titular varchar(255),
        primary key (id)
    ) engine=InnoDB
Exception in thread "main" java.lang.IllegalStateException: Transaction not successfully started
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:92)
    at br.com.caelum.financas.teste.TestaConta.main(TestaConta.java:24)código aqui
4 respostas

Bom dia Eduardo, pode colocar seu código aqui por favor?

package br.com.caelum.financas.modelo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.*;


@Entity    //Conta é uma entidade
public class Conta {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)  //Declarando que é um id com estrategia de auto-incremento
    private Integer id;
    private String agencia;
    private String numero;
    private String banco;
    private String titular;


    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getAgencia() {
        return agencia;
    }
    public void setAgencia(String agencia) {
        this.agencia = agencia;
    }
    public String getNumero() {
        return numero;
    }
    public void setNumero(String numero) {
        this.numero = numero;
    }
    public String getBanco() {
        return banco;
    }
    public void setBanco(String banco) {
        this.banco = banco;
    }
    public String getTitular() {
        return titular;
    }
    public void setTitular(String titular) {
        this.titular = titular;
    }


}
package br.com.caelum.financas.teste;

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

import br.com.caelum.financas.modelo.Conta;

public class TestaConta {

    public static void main(String[] args) {

        Conta conta = new Conta();
        conta.setAgencia("123");
        conta.setBanco("Caixa Econômica");
        conta.setNumero("456");
        conta.setTitular("Eduardo França");

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

        em.getTransaction().begin();                            //Abrindo a transação
        em.persist(conta);                                    //Persistindo a referencia conta (como nao existe a tabela, o hibernate cria).
        em.close();


        em.getTransaction().commit();
        emf.close();
    }
}
<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>br.com.caelum.financas.modelo.Conta</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="12345" />

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

Eu resolvi o primeiro problema, agora ta aparecendo esse:

Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named financas
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at br.com.caelum.financas.teste.TestaConta.main(TestaConta.java:19)
solução!

Novo erro:

jun 13, 2018 9:41:35 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: financas
    ...]
jun 13, 2018 9:41:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.1.Final}
jun 13, 2018 9:41:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
jun 13, 2018 9:41:35 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.3.Final}
jun 13, 2018 9:41:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
jun 13, 2018 9:41:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/financas]
jun 13, 2018 9:41:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
jun 13, 2018 9:41:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
jun 13, 2018 9:41:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Wed Jun 13 21:41:36 BRT 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
jun 13, 2018 9:41:36 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
jun 13, 2018 9:41:38 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@36c54a56] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: 
    insert 
    into
        Conta
        (agencia, banco, numero, titular) 
    values
        (?, ?, ?, ?)
jun 13, 2018 9:41:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost/financas]
jun 13, 2018 9:41:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections close
ERROR: Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://localhost/financas