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

Erro ao Tentar Inserir Objetos Relacionados no Banco

Pessoal, estou tentando inserir 2 objetos que possuem um relacionamento @OneToMany, mas não estou conseguindo efetuar a inserção no meu banco.

Isso é o que estou tentando fazer:

package main;

import java.util.List;

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

import modelo.Dia; import modelo.Hora;

public class Main {

    private static List<Hora> horas;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        EntityManagerFactory factory = Persistence.createEntityManagerFactory("PrimeiroDrop");
        EntityManager manager = factory.createEntityManager();
        EntityTransaction tx = manager.getTransaction();

        Dia dia = new Dia();
        Hora hora = new Hora();

        dia.setDia("Terça-Feira");


        hora.setHora_inicial("05:30");
        hora.setHora_final("06:30");

        horas = null;

        horas.add(hora);

        dia.setHoras(horas);

        tx.begin();
        manager.merge(dia);
        tx.commit();
        manager.close();    

    }

}

Entity Dia:

package modelo;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Dia {

    @Id @GeneratedValue
    private Long id;

    @Column(nullable=false)
    private String dia;

    @OneToMany
    private List<Hora> horas;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDia() {
        return dia;
    }

    public void setDia(String dia) {
        this.dia = dia;
    }

    public List<Hora> getHoras() {
        return horas;
    }

    public void setHoras(List<Hora> horas) {
        this.horas = horas;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((dia == null) ? 0 : dia.hashCode());
        result = prime * result + ((horas == null) ? 0 : horas.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Dia other = (Dia) obj;
        if (dia == null) {
            if (other.dia != null)
                return false;
        } else if (!dia.equals(other.dia))
            return false;
        if (horas == null) {
            if (other.horas != null)
                return false;
        } else if (!horas.equals(other.horas))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }


}

Entity Hora:

package modelo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Hora {

    @Id @GeneratedValue
    private Long id;

    @Column(nullable=false)
    private String hora_inicial;

    @Column(nullable=false)
    private String hora_final;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getHora_inicial() {
        return hora_inicial;
    }

    public void setHora_inicial(String hora_inicial) {
        this.hora_inicial = hora_inicial;
    }

    public String getHora_final() {
        return hora_final;
    }

    public void setHora_final(String hora_final) {
        this.hora_final = hora_final;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((hora_final == null) ? 0 : hora_final.hashCode());
        result = prime * result
                + ((hora_inicial == null) ? 0 : hora_inicial.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Hora other = (Hora) obj;
        if (hora_final == null) {
            if (other.hora_final != null)
                return false;
        } else if (!hora_final.equals(other.hora_final))
            return false;
        if (hora_inicial == null) {
            if (other.hora_inicial != null)
                return false;
        } else if (!hora_inicial.equals(other.hora_inicial))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }


}

O erro que está aparecendo no console é:

03/07/2014 15:36:49 org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
03/07/2014 15:36:49 org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
03/07/2014 15:36:49 org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
03/07/2014 15:36:50 org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: PrimeiroDrop
    ...]
03/07/2014 15:36:51 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
03/07/2014 15:36:51 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
03/07/2014 15:36:51 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
03/07/2014 15:36:52 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
03/07/2014 15:36:52 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
03/07/2014 15:36:52 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/PrimeiroDrop]
03/07/2014 15:36:52 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=postgres, password=****}
03/07/2014 15:36:52 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
03/07/2014 15:36:52 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
03/07/2014 15:36:54 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
03/07/2014 15:36:54 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
03/07/2014 15:36:54 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: public.dia
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [id, dia]
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [dia_pkey]
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: public.dia_hora
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [horas_id, dia_id]
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_ini6iux53r7ib8hxj5jgh30c2, fk_a0ra0no37euiiov5y7tfucnbj]
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [uk_a0ra0no37euiiov5y7tfucnbj]
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: public.hora
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [id, hora_inicial, hora_final]
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [hora_pkey]
03/07/2014 15:36:55 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Exception in thread "main" java.lang.NullPointerException
    at main.Main.main(Main.java:35)

Novo erro gerado:

xception in thread "main" javax.persistence.RollbackException: Error while committing the transaction
    at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:94)
    at main.Main.main(Main.java:42)
Caused by: java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: modelo.Hora
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1760)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:82)
    ... 1 more
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: modelo.Hora
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
    at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:165)
    at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:899)
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1308)
    at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
    at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
    ... 1 more
  • Seu problema é NullPointer, fera, debbuga seu programa pra saber que que você está tentando persistir e esta Nulo.

    lucasgarofolo   03 de jul de 2014
  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 jsf hibernate jpa ou faça a sua própria pergunta.