Hibernate does not save oneToMany

Asked

Viewed 73 times

0

I have a 1 -> n relationship between Connection and Reporting. The classes are as follows::

@Entity
@Table(name = "conexao")
public class Conexao {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "CONEXAO_ID", unique = true, nullable = false)
 private Long id;

@OneToMany(fetch = FetchType.LAZY, mappedBy="conexao")
private Set<Relatorio> relatorios;

  //getters and setters
}

The Reporterio class:

@Entity
@Table(name = "relatorio")

public class Relatorio {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "RELATORIO_ID", unique = true, nullable = false)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CONEXAO_ID")    
private Conexao conexao;

public Relatorio(Conexao conexao){
       this.coxexao = conexao;
}
   //getters and setters
}

I’m running like this:

   public Teste(){
   ConexaoDao  conDao = new ConexaoDao();
   Conexao con = conDao.buscar(new Long(6)); // aqui, tudo certo, ele tras a 
   conexao corretamente

  Relatorio relatorio = new Relatorio(con, "teste777", "teste555", "teste333");
  con.getRelatorios().add(relatorio);

  RelatorioDAO relDao = new RelatorioDAO();
  relDao.salvar(relatorio); // ele salva o relatorio, com a conexao preenchida corretamente

  }
}

Os Daos:

public class ConexaoDAO {


public void salvar(Conexao conexao){
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Transaction transacao = sessao.beginTransaction();
    sessao.save(conexao);
    transacao.commit();
    sessao.close();
}

public void editar(List<Conexao> lista){
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Transaction transacao = sessao.beginTransaction();
    lista.forEach(conexao -> sessao.update(conexao));
    transacao.commit();
    sessao.close();
}

public void excluir(List<Conexao> lista){
    excluirRelatorio(lista);

    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Transaction transacao = sessao.beginTransaction();
    Query query;
    for(Conexao conexao: lista){
        query = sessao.createQuery("delete Conexao where id = :id");
        query.setParameter("id", conexao.getId());
        query.executeUpdate();
    }
    transacao.commit();
    sessao.close();

}

private void excluirRelatorio(List<Conexao> lista){
    List<Relatorio> listaRelatorioExclusaoDummy = new ArrayList<Relatorio>();
    Set<Relatorio> setDummy;

    for(Conexao conexao: lista){
        setDummy = conexao.getRelatorios();
        listaRelatorioExclusaoDummy.addAll(setDummy);
    }
    RelatorioDAO relatorioDao = new RelatorioDAO();
    relatorioDao.excluir(listaRelatorioExclusaoDummy);
}



public List<Conexao> listar(){
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Query query = sessao.createQuery("from Conexao"); 
    List<Conexao> conexoes = query.list();
    sessao.close();
    return conexoes;
}


public Conexao buscar(Long id){
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Conexao conexao = (Conexao) sessao.get(Conexao.class, id);
    sessao.close();
    return conexao;
}

public void excluir(Conexao conexao){
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Transaction transacao = sessao.beginTransaction();
    sessao.delete(conexao);
    transacao.commit();
    sessao.close();
}

public void editar(Conexao conexao){
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Transaction transacao = sessao.beginTransaction();
    sessao.update(conexao);
    transacao.commit();
    sessao.close();
}


}

And Report:

public class RelatorioDAO{

public void excluir(List<Relatorio> lista) {
    excluirColuna(lista);

    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Transaction transacao = sessao.beginTransaction();
    Query query;
    for(Relatorio relatorio: lista){
        query = sessao.createQuery("delete Relatorio where id = :id");
        query.setParameter("id", relatorio.getId());
        query.executeUpdate();
    }
    transacao.commit();
    sessao.close();
}

private void excluirColuna(List<Relatorio> lista){
    List<Coluna> listaColunaExclusaoDummy = new ArrayList<Coluna>();
    Set<Coluna> setDummy;

    for(Relatorio relatorio: lista){
        setDummy = relatorio.getColunas();
        listaColunaExclusaoDummy.addAll(setDummy);
    }
    ColunaDAO colunaDao = new ColunaDAO();
    colunaDao.excluir(listaColunaExclusaoDummy);
}

public void editar(List<Relatorio> listaRelatorioDummy) {
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Transaction transacao = sessao.beginTransaction();

    listaRelatorioDummy.forEach(relatorio -> sessao.update(relatorio));

    transacao.commit();
    sessao.close();
}

public void salvar(Relatorio relatorio) {
    Session sessao= null;
    try{
        sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = sessao.beginTransaction();
        sessao.save(relatorio);
        transacao.commit();
    }finally{
        sessao.close();
    }
}

public List<Relatorio> listar() {
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Query query = sessao.createQuery("from Relatorio"); 
    List<Relatorio> relatorios = query.list();
    sessao.close();
    return relatorios;
}


}

and my Hibernateutil class:

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate.cfg.xml
        return new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

public static void shutdown() {
    // Close caches and connection pools
    getSessionFactory().close();
}
}

However, when I load the report, it brings the connection with the null fields. Being that when I debugged the code, I verified that the connection passed as parameter to the Report constructor, is filled in all fields.

The strange thing is that when I look at Postgres, the report table, has the CONEXAO_ID column filled out correctly. I do not understand why Java is not bringing the connection with all nulls. The connection brought is not null, but its fields yes. Someone could help me???

I’ll put the images to be more explicit:

This image shows the connection set in report. As you can see, the connection fields are all filled. Campos da conexão preenchidos

Quando listo todos os relatórios e verifico o qual acabei de salvar, a conexão que na linha acima estava preenchida, agora vem com todos os campos nulos

  • Hello, thank you for the answer.. but I believe that is not so, since I make a query next and the returned fields are null. I put an image to illustrate what happens

  • Enter your DAO code. Values must be null because someone must be closing the connection.

  • Hi Giuliana, thanks for your help. I put the classes there

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.