-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 
Author Message
 Post subject: Only one table is commited, what about the others?
PostPosted: Tue Feb 08, 2005 1:28 pm 
Beginner
Beginner

Joined: Fri Apr 16, 2004 10:25 am
Posts: 44
Location: Brazil
Hibernate version: 2.1.8

Code ParceirosBO:
Code:
   public boolean inserir(parceiroVO parceiro, empresaVO empresa, Collection colProfiles) {

      try {
         ParceirosDAO parceirosDAO = new ParceirosDAO();
         ParceirosEmpresaDAO parceiroEmpresaDAO = new ParceirosEmpresaDAO();
         ParceirosProfileDAO parceiroProfileDAO = new ParceirosProfileDAO();
      
         // Inserir Parceiro
         logger.debug("Inserir Parceiro");
         
         parceiro.setVchsenhaftp("definir");

         
         logger.debug("Inserir Empresa do Parceiro");
         // Inserir Empresa do Parceiro
         parceiroEmpresaVOPK parceiroEPK = new parceiroEmpresaVOPK();
         parceiroEmpresaVO parceiroE = new parceiroEmpresaVO();
         parceiroEPK.setIdEmpresa(empresa.getIdEmpresa());
         parceiroEPK.setIdParceiro(parceiro.getIdParceiro());
         parceiroE.setComp_id(parceiroEPK);
//         parceiroEmpresaDAO.makePersistent(parceiroE);
         Set parceirosE = new HashSet();
         parceirosE.add(parceiroE);
         parceiro.setParceiroempresavo(parceirosE);

         // Inserir Profiles do Parceiro
         logger.debug("Inserir Profiles do Parceiro");
         Iterator it = colProfiles.iterator();
         Set parceirosP = new HashSet();
         while (it.hasNext()) {
            profileVO profile = (profileVO) it.next();
            parceiroProfileVOPK parceiroPPK = new parceiroProfileVOPK();
            parceiroProfileVO parceiroP = new parceiroProfileVO();
            parceiroPPK.setIdProfile(profile.getIdProfile());
            parceiroPPK.setIdParceiro(parceiro.getIdParceiro());
            parceiroP.setComp_id(parceiroPPK);
//            parceiroProfileDAO.makePersistent(parceiroP);
            parceirosP.add(parceiroP);
         }
         parceiro.setParceiroprofilevo(parceirosP);
         
         parceirosDAO.makePersistent(parceiro);

         logger.debug("Fazendo Commit das alteracoes");
         HibernateUtil.commitTransaction();
         HibernateUtil.closeSession();
         return true;
      } catch (Exception e) {
         logger.debug("ParceirosBO.inserir ERRO =" + e);
         return false;
         
      }

   }


Code ParceirosDAO:
Code:
package com.bzo2.lupo.dao;

import net.sf.hibernate.HibernateException;

import org.apache.log4j.Category;

import com.bzo2.lupo.exceptions.DAOException;
import com.bzo2.lupo.utils.HibernateUtil;
import com.bzo2.lupo.vo.empresaVO;
import com.bzo2.lupo.vo.parceiroVO;

public class ParceirosDAO extends Dao {

    static Category logger = Category.getInstance(ParceirosDAO.class);

   public ParceirosDAO() throws DAOException {
      super();
   }
   
   public boolean delete(Long idParceiro) throws DAOException {
          parceiroVO parceiro = null;
          try{
                 parceiro = findByPrimaryKey(idParceiro);
              HibernateUtil.getSession().delete(parceiro);
             return true;
          }catch(HibernateException he){
              logger.error("ParceirosBO.delete ERRO :\n"+he);
              return false;
          }
   }

   public parceiroVO findByPrimaryKey(Long idParceiro) throws DAOException {
      parceiroVO parceiro = null;
          try{
               parceiro = (parceiroVO) HibernateUtil.getSession().load(empresaVO.class,idParceiro);
            
             return parceiro;
          }catch(HibernateException he){
              logger.error("ParceirosBO.findByPrimaryKey ERRO :\n"+he);
              return null;
          }
   }
}


Code ParceirosEmpresasDAO
Code:
package com.bzo2.lupo.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;

import org.apache.log4j.Category;

import com.bzo2.lupo.exceptions.DAOException;
import com.bzo2.lupo.utils.HibernateUtil;
import com.bzo2.lupo.vo.parceiroEmpresaVO;

public class ParceirosEmpresaDAO extends Dao {
   static Category logger = Category.getInstance(ParceirosEmpresaDAO.class);

   public ParceirosEmpresaDAO() throws DAOException {
      super();
   }

   public Collection findByEmpresa(Long idEmpresa) throws DAOException {
      try {
         ArrayList col = new ArrayList();
         Query query = HibernateUtil.getSession()
               .createQuery("select o from parceiroEmpresaVO as o where o.empresaVO = :empresa");
         query.setLong("empresa", idEmpresa.longValue());
         Iterator it = query.iterate();
         while (it.hasNext()) {
            parceiroEmpresaVO parceiroEmpresa = (parceiroEmpresaVO) it.next();
            col.add(parceiroEmpresa);
         }
         return col;
      } catch (HibernateException he) {
         logger.error("ParceirosEmpresaDAO.findByPerfil ERRO :\n" + he);
         return null;
      }
   }

   public Collection findByParceiro(Long idParceiro) throws DAOException {
      try {
         ArrayList col = new ArrayList();
         Query query = HibernateUtil.getSession()
               .createQuery("select o from parceiroEmpresaVO as o where o.parceiroVO = :parceiro");
         query.setLong("parceiro", idParceiro.longValue());
         Iterator it = query.iterate();
         while (it.hasNext()) {
            parceiroEmpresaVO parceiroEmpresa = (parceiroEmpresaVO) it.next();
            col.add(parceiroEmpresa);
         }
         return col;
      } catch (HibernateException he) {
         logger.error("ParceirosEmpresaDAO.findByPerfil ERRO :\n" + he);
         return null;
      }
   }
}


Code HibernateUtil :
Code:
package com.bzo2.lupo.utils;

import java.net.URL;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Interceptor;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bzo2.lupo.exceptions.DAOException;

/**
* Basic Hibernate helper class, handles SessionFactory, Session and Transaction.
* <p>
* Uses a static initializer for the initial SessionFactory creation
* and holds Session and Transactions in thread local variables. All
* exceptions are wrapped in an unchecked InfrastructureException.
*
* @author christian@hibernate.org
*/
public class HibernateUtil {

   private static Log log = LogFactory.getLog(HibernateUtil.class);

   private static Configuration configuration;
   private static SessionFactory sessionFactory;
   private static final ThreadLocal threadSession = new ThreadLocal();
   private static final ThreadLocal threadTransaction = new ThreadLocal();
   private static final ThreadLocal threadInterceptor = new ThreadLocal();

   // Create the initial SessionFactory from the default configuration files
   static {
      try {
         //configuration = new Configuration();
         //sessionFactory = configuration.configure().buildSessionFactory();
         URL url = HibernateUtil.class.getResource("/hibernate.cfg.xml");
            sessionFactory = new Configuration().configure(url).buildSessionFactory();
         
         // We could also let Hibernate bind it to JNDI:
         // configuration.configure().buildSessionFactory()
      } catch (Throwable ex) {
         // We have to catch Throwable, otherwise we will miss
         // NoClassDefFoundError and other subclasses of Error
         log.error("Building SessionFactory failed.", ex);
         throw new ExceptionInInitializerError(ex);
      }
   }

   /**
    * Returns the SessionFactory used for this static class.
    *
    * @return SessionFactory
    */
   public static SessionFactory getSessionFactory() {
      /* Instead of a static variable, use JNDI:
      SessionFactory sessions = null;
      try {
         Context ctx = new InitialContext();
         String jndiName = "java:hibernate/HibernateFactory";
         sessions = (SessionFactory)ctx.lookup(jndiName);
      } catch (NamingException ex) {
         throw new InfrastructureException(ex);
      }
      return sessions;
      */
      return sessionFactory;
   }

   /**
    * Returns the original Hibernate configuration.
    *
    * @return Configuration
    */
   public static Configuration getConfiguration() {
      return configuration;
   }

   /**
    * Rebuild the SessionFactory with the static Configuration.
    *
    */
    public static void rebuildSessionFactory()
      throws DAOException {
      synchronized(sessionFactory) {
         try {
            sessionFactory = getConfiguration().buildSessionFactory();
         } catch (Exception ex) {
            throw new DAOException(ex);
         }
      }
    }

   /**
    * Rebuild the SessionFactory with the given Hibernate Configuration.
    *
    * @param cfg
    */
    public static void rebuildSessionFactory(Configuration cfg)
      throws DAOException {
      synchronized(sessionFactory) {
         try {
            sessionFactory = cfg.buildSessionFactory();
            configuration = cfg;
         } catch (Exception ex) {
            throw new DAOException(ex);
         }
      }
    }

   /**
    * Retrieves the current Session local to the thread.
    * <p/>
    * If no Session is open, opens a new Session for the running thread.
    *
    * @return Session
    */
   public static Session getSession()
      throws DAOException {
      Session s = (Session) threadSession.get();
      try {
         if (s == null) {
            log.debug("Opening new Session for this thread.");
            if (getInterceptor() != null) {
               log.debug("Using interceptor: " + getInterceptor().getClass());
               s = getSessionFactory().openSession(getInterceptor());
            } else {
               s = getSessionFactory().openSession();
            }
            threadSession.set(s);
         }
      } catch (HibernateException ex) {
         throw new DAOException(ex);
      }
      return s;
   }

   /**
    * Closes the Session local to the thread.
    */
   public static void closeSession()
      throws DAOException {
      try {
         Session s = (Session) threadSession.get();
         threadSession.set(null);
         if (s != null && s.isOpen()) {
            log.debug("Closing Session of this thread.");
            s.close();
         }
      } catch (HibernateException ex) {
         throw new DAOException(ex);
      }
   }

   /**
    * Start a new database transaction.
    */
   public static void beginTransaction()
      throws DAOException {
      Transaction tx = (Transaction) threadTransaction.get();
      try {
         if (tx == null) {
            log.debug("Starting new database transaction in this thread.");
            tx = getSession().beginTransaction();
            threadTransaction.set(tx);
         }
      } catch (HibernateException ex) {
         throw new DAOException(ex);
      }
   }

   /**
    * Commit the database transaction.
    */
   public static void commitTransaction()
      throws DAOException {
      Transaction tx = (Transaction) threadTransaction.get();
      try {
         if ( tx != null && !tx.wasCommitted()
                     && !tx.wasRolledBack() ) {
            log.debug("Committing database transaction of this thread.");
            tx.commit();
         }
         threadTransaction.set(null);
      } catch (HibernateException ex) {
         rollbackTransaction();
         throw new DAOException(ex);
      }
   }

   /**
    * Commit the database transaction.
    */
   public static void rollbackTransaction()
      throws DAOException {
      Transaction tx = (Transaction) threadTransaction.get();
      try {
         threadTransaction.set(null);
         if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
            log.debug("Trying to rollback database transaction of this thread.");
            tx.rollback();
         }
      } catch (HibernateException ex) {
         throw new DAOException(ex);
      } finally {
         closeSession();
      }
   }

   /**
    * Reconnects a Hibernate Session to the current Thread.
    *
    * @param session The Hibernate Session to be reconnected.
    */
   public static void reconnect(Session session)
      throws DAOException {
      try {
         session.reconnect();
         threadSession.set(session);
      } catch (HibernateException ex) {
         throw new DAOException(ex);
      }
   }

   /**
    * Disconnect and return Session from current Thread.
    *
    * @return Session the disconnected Session
    */
   public static Session disconnectSession()
      throws DAOException {

      Session session = getSession();
      try {
         threadSession.set(null);
         if (session.isConnected() && session.isOpen())
            session.disconnect();
      } catch (HibernateException ex) {
         throw new DAOException(ex);
      }
      return session;
   }

   /**
    * Register a Hibernate interceptor with the current thread.
    * <p>
    * Every Session opened is opened with this interceptor after
    * registration. Has no effect if the current Session of the
    * thread is already open, effective on next close()/getSession().
    */
   public static void registerInterceptor(Interceptor interceptor) {
      threadInterceptor.set(interceptor);
   }

   private static Interceptor getInterceptor() {
      Interceptor interceptor =
         (Interceptor) threadInterceptor.get();
      return interceptor;
   }

}



Code Dao :
Code:
/*
* Created on 07/02/2005
*/
package com.bzo2.lupo.dao;

import net.sf.hibernate.HibernateException;

import org.apache.log4j.Category;

import com.bzo2.lupo.exceptions.DAOException;
import com.bzo2.lupo.utils.HibernateUtil;

/**
* @author Marcel Keiti Toma
*/
public abstract class Dao {
   static Category logger = Category.getInstance(Dao.class);
   
   public Dao() throws DAOException {
      HibernateUtil.beginTransaction();
   }
   
   public void makePersistent(Object o) throws DAOException {
      try {
//         Transaction tx = session.beginTransaction();

         HibernateUtil.getSession().saveOrUpdate(o);
         
         logger.debug("makePersistent "+o.getClass().getName());
//         tx.commit();
      } catch (HibernateException e) {
         logger.debug("DAO.makePersistent ERRO = "+e);
         throw new DAOException(e.getMessage());
      }
   }

   public void makeTransient(Object o) throws DAOException {
      try {
         HibernateUtil.getSession().delete(o);
      } catch (HibernateException e) {
         logger.debug("DAO.makeTransient ERRO = "+e);
         throw new DAOException(e.getMessage());
      }
   }
}


Full stack trace of any exception that occurs:
Code:
INFO [http-8080-Processor23] (ParceirosAction.java:58) - Inserindo parceiro
DEBUG [http-8080-Processor23] (ParceirosBO.java:43) - Inserir Parceiro
DEBUG [http-8080-Processor23] (ParceirosBO.java:48) - Inserir Empresa do Parceiro
DEBUG [http-8080-Processor23] (ParceirosBO.java:61) - Inserir Profiles do Parceiro
DEBUG [http-8080-Processor23] (Dao.java:29) - makePersistent com.bzo2.lupo.vo.parceiroVO
DEBUG [http-8080-Processor23] (ParceirosBO.java:78) - Fazendo Commit das alteracoes
DEBUG [http-8080-Processor23] (HibernateUtil.java:185) - Committing database transaction of this thread.
Hibernate: insert into LUPO_PARCEIROS (VCHSENHAFTP, VCHNOMEEMPRESA, VCHUSUARIO, VCHSENHA, VCHNOME, VCHSTATUS, ID_TIPOMEDIA, ID_PARCEIRO) values (?, ?, ?, ?, ?, ?, ?, ?)
DEBUG [http-8080-Processor23] (HibernateUtil.java:151) - Closing Session of this thread.


Name and version of the database you are using: Oracle 8i
[/code]


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 08, 2005 1:29 pm 
Beginner
Beginner

Joined: Fri Apr 16, 2004 10:25 am
Posts: 44
Location: Brazil
Mapping documents:
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
   
<hibernate-mapping>
<!--
    Created by the Middlegen Hibernate plugin 2.1

    http://boss.bekk.no/boss/middlegen/
    http://www.hibernate.org/
-->

<class
    name="com.bzo2.lupo.vo.parceiroVO"
    table="LUPO_PARCEIROS"
>

    <id
        name="idParceiro"
        type="java.lang.Long"
        column="ID_PARCEIRO"
    >
        <generator class="increment" />
    </id>

    <property
        name="vchsenhaftp"
        type="java.lang.String"
        column="VCHSENHAFTP"
        not-null="true"
        length="18"
    />
    <property
        name="vchnomeempresa"
        type="java.lang.String"
        column="VCHNOMEEMPRESA"
        not-null="true"
        length="200"
    />
    <property
        name="vchusuario"
        type="java.lang.String"
        column="VCHUSUARIO"
        not-null="true"
        length="50"
    />
    <property
        name="vchsenha"
        type="java.lang.String"
        column="VCHSENHA"
        not-null="true"
        length="50"
    />
    <property
        name="vchnome"
        type="java.lang.String"
        column="VCHNOME"
        not-null="true"
        length="250"
    />
    <property
        name="vchstatus"
        type="java.lang.String"
        column="VCHSTATUS"
        not-null="true"
        length="1"
    />

    <!-- Associations -->
 
    <!-- bi-directional one-to-many association to parceiroProfileVO -->
    <set
        name="parceiroprofilevo"
        lazy="true"
        inverse="true"
      cascade="all"
    >
        <key>
            <column name="ID_PARCEIRO" />
        </key>
        <one-to-many
            class="com.bzo2.lupo.vo.parceiroProfileVO"
        />
    </set>
    <!-- bi-directional one-to-many association to parceiroEmpresaVO -->
    <set
        name="parceiroempresavo"
        lazy="true"
        inverse="true"
      cascade="all"
    >
        <key>
            <column name="ID_PARCEIRO" />
        </key>
        <one-to-many
            class="com.bzo2.lupo.vo.parceiroEmpresaVO"
        />
    </set>
    <!-- bi-directional many-to-one association to tipoMediaVO -->
    <many-to-one
        name="tipoMediaVO"
        class="com.bzo2.lupo.vo.tipoMediaVO"
        not-null="true"
    >
        <column name="ID_TIPOMEDIA" />
    </many-to-one>

</class>
</hibernate-mapping>

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
   
<hibernate-mapping>
<!--
    Created by the Middlegen Hibernate plugin 2.1

    http://boss.bekk.no/boss/middlegen/
    http://www.hibernate.org/
-->

<class
    name="com.bzo2.lupo.vo.parceiroProfileVO"
    table="LUPO_PARCEIRO_PROFILES"
>

    <composite-id name="comp_id" class="com.bzo2.lupo.vo.parceiroProfileVOPK">
        <key-property
            name="idParceiro"
            column="ID_PARCEIRO"
            type="java.lang.Long"
            length="38"
        />
        <key-property
            name="idProfile"
            column="ID_PROFILE"
            type="java.lang.Long"
            length="38"
        />
    </composite-id>   


    <!-- Associations -->
    <!-- derived association(s) for compound key -->
    <!-- bi-directional many-to-one association to profileVO -->
    <many-to-one
        name="profileVO"
       class="com.bzo2.lupo.vo.profileVO"
       update="false"
       insert="false"
   >
       <column name="ID_PROFILE" />
   </many-to-one>
   
    <!-- bi-directional many-to-one association to parceiroVO -->
    <many-to-one
        name="parceiroVO"
       class="com.bzo2.lupo.vo.parceiroVO"
       update="false"
       insert="false"
   >
       <column name="ID_PARCEIRO" />
   </many-to-one>
   
    <!-- end of derived association(s) -->
 

</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
   
<hibernate-mapping>
<!--
    Created by the Middlegen Hibernate plugin 2.1

    http://boss.bekk.no/boss/middlegen/
    http://www.hibernate.org/
-->

<class
    name="com.bzo2.lupo.vo.parceiroEmpresaVO"
    table="LUPO_PARCEIROS_EMPRESAS"
>

    <composite-id name="comp_id" class="com.bzo2.lupo.vo.parceiroEmpresaVOPK">
        <key-property
            name="idParceiro"
            column="ID_PARCEIRO"
            type="java.lang.Long"
            length="38"
        />
        <key-property
            name="idEmpresa"
            column="ID_EMPRESA"
            type="java.lang.Long"
            length="38"
        />
    </composite-id>   


    <!-- Associations -->
    <!-- derived association(s) for compound key -->
    <!-- bi-directional many-to-one association to empresaVO -->
    <many-to-one
        name="empresaVO"
       class="com.bzo2.lupo.vo.empresaVO"
       update="false"
       insert="false"
   >
       <column name="ID_EMPRESA" />
   </many-to-one>
   
    <!-- bi-directional many-to-one association to parceiroVO -->
    <many-to-one
        name="parceiroVO"
       class="com.bzo2.lupo.vo.parceiroVO"
       update="false"
       insert="false"
   >
       <column name="ID_PARCEIRO" />
   </many-to-one>
   
    <!-- end of derived association(s) -->
 

</class>
</hibernate-mapping>


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 08, 2005 3:13 pm 
Beginner
Beginner

Joined: Fri Apr 16, 2004 10:25 am
Posts: 44
Location: Brazil
Looks like its a problem with saveOrUpdate


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 08, 2005 3:21 pm 
Beginner
Beginner

Joined: Fri Apr 16, 2004 10:25 am
Posts: 44
Location: Brazil
I changed saveOrUpdate to save and now it works
=)


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.