-->
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: Collection prblem
PostPosted: Wed May 24, 2006 6:00 pm 
Newbie

Joined: Wed May 24, 2006 5:47 pm
Posts: 14
Ho all.
I'm newbie to hibernate.
I'm using this environment


Hibernate version: 3.1.3 .
JVM: 1.5.0_06-b05
RBBMS: MySQL 5

I have two tables: Menu and SottoMenu; the SottoMenu is a children of Menu.
I have used these mapping files:


SottoMenu:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 20-mag-2006 11.09.56 by Hibernate Tools 3.1.0 beta3 -->
<hibernate-mapping>
<class name="it.eng.hibernate.util.db.SottoMenu" table="sotto_menu" catalog="galleriacorso">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<many-to-one name="menu" class="it.eng.hibernate.util.db.Menu" fetch="select">
<column name="ID_MENU" not-null="true" />
</many-to-one>
<property name="nome" type="string">
<column name="NOME" length="100" not-null="true" />
</property>
<property name="nomePagina" type="string">
<column name="NOME_PAGINA" length="100" not-null="true" />
</property>
</class>
</hibernate-mapping>

Menu:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 20-mag-2006 11.09.56 by Hibernate Tools 3.1.0 beta3 -->
<hibernate-mapping>
<class name="it.eng.hibernate.util.db.Menu" table="menu" catalog="galleriacorso">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="nome" type="string">
<column name="NOME" length="100" not-null="true" />
</property>
<property name="nomePagina" type="string">
<column name="NOME_PAGINA" length="100" />
</property>
<set name="sottoMenus" inverse="true">
<key>
<column name="ID_MENU" not-null="true" />
</key>
<one-to-many class="it.eng.hibernate.util.db.SottoMenu" />
</set>
</class>
</hibernate-mapping>


By using JBossIDE i have obtained these java classes:


Menu.java:
Code:
package it.eng.hibernate.util.db;
// Generated 20-mag-2006 11.09.56 by Hibernate Tools 3.1.0 beta3

import java.util.HashSet;
import java.util.Set;


/**
* Menu generated by hbm2java
*/

public class Menu  implements java.io.Serializable {


    // Fields   

     private int id;
     private String nome;
     private String nomePagina;
     private Set<SottoMenu> sottoMenus = new HashSet<SottoMenu>(0);


    // Constructors

    /** default constructor */
    public Menu() {
    }

   /** minimal constructor */
    public Menu(int id, String nome) {
        this.id = id;
        this.nome = nome;
    }
   
    /** full constructor */
    public Menu(int id, String nome, String nomePagina, Set<SottoMenu> sottoMenus) {
        this.id = id;
        this.nome = nome;
        this.nomePagina = nomePagina;
        this.sottoMenus = sottoMenus;
    }
   

   
    // Property accessors

    public int getId() {
        return this.id;
    }
   
    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return this.nome;
    }
   
    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getNomePagina() {
        return this.nomePagina;
    }
   
    public void setNomePagina(String nomePagina) {
        this.nomePagina = nomePagina;
    }

    public Set<SottoMenu> getSottoMenus() {
        return this.sottoMenus;
    }
   
    public void setSottoMenus(Set<SottoMenu> sottoMenus) {
        this.sottoMenus = sottoMenus;
    }
}

SottoMenu.java:
Code:
package it.eng.hibernate.util.db;
// Generated 20-mag-2006 11.09.56 by Hibernate Tools 3.1.0 beta3



/**
* SottoMenu generated by hbm2java
*/

public class SottoMenu  implements java.io.Serializable {


    // Fields   

     private int id;
     private Menu menu;
     private String nome;
     private String nomePagina;


    // Constructors

    /** default constructor */
    public SottoMenu() {
    }

   
    /** full constructor */
    public SottoMenu(int id, Menu menu, String nome, String nomePagina) {
        this.id = id;
        this.menu = menu;
        this.nome = nome;
        this.nomePagina = nomePagina;
    }
   

   
    // Property accessors

    public int getId() {
        return this.id;
    }
   
    public void setId(int id) {
        this.id = id;
    }

    public Menu getMenu() {
        return this.menu;
    }
   
    public void setMenu(Menu menu) {
        this.menu = menu;
    }

    public String getNome() {
        return this.nome;
    }
   
    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getNomePagina() {
        return this.nomePagina;
    }
   
    public void setNomePagina(String nomePagina) {
        this.nomePagina = nomePagina;
    }
}

PersistentDataAccess:
Code:
package it.eng.hibernate.util.mgr;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import org.apache.log4j.Logger;

public abstract class PersistentDataAccess {
   
    private static final Logger LOG = Logger.getLogger( PersistentDataAccess.class.getName() );

    public static Object create(Object po) throws DBRuntimeException {
        try {
          Session session = DBSessionMgr.getActiveSession();
          session.save(po);
        } catch (HibernateException e) {
          LOG.error("Problem when creating a persistent object.", e);
          throw new DBRuntimeException(e);
        } catch (DBSessionException e) {
          LOG.error("Problem when updating a persistent object.", e);
          throw new DBRuntimeException(e);
        }

        return po;
      }

      public static Object update(Object po) throws DBRuntimeException {

        try {
          Session session = DBSessionMgr.getActiveSession();
          session.saveOrUpdate(po);
        } catch (HibernateException e) {
          LOG.error("Problem when updating a persistent object.", e);
          throw new DBRuntimeException(e);
        } catch (DBSessionException e) {
          LOG.error("Problem when updating a persistent object.", e);
          throw new DBRuntimeException(e);
        }

        return po;
      }

      public static Object remove(Object po) throws DBRuntimeException {
        try {
          Session session = DBSessionMgr.getActiveSession();
          session.delete(po);
        } catch (HibernateException e) {
          LOG.error("Problem when removing a persistent object.", e);
          throw new DBRuntimeException(e);
        } catch (DBSessionException e) {
          LOG.error("Problem when removing a persistent object.", e);
          throw new DBRuntimeException(e);
        }

        return po;
      }

      public static Object findById(Long id, Class classToLoad) throws DBRuntimeException, FinderException {
        Object po = null;
        try {
          Session session = DBSessionMgr.getDBReadSession();
          po = session.load(classToLoad, id);
          DBSessionMgr.closeDBReadSession(session);
        } catch (HibernateException e) {
          LOG.error("Problem while searching an object from POJO class: "+classToLoad.getName()+" and id: "+id+".", e);
          throw new DBRuntimeException(e);
        } catch (DBSessionException e) {
          LOG.error("Problem while searching an object from POJO class: "+classToLoad.getName()+" and id: "+id+".", e);
          throw new DBRuntimeException(e);
        }
        if (po == null) {
          throw new FinderException("Couldn't find a " + classToLoad + " with id : " + id);
        }

        return po;
      }

      public static List findAll(Class classToLoad) throws DBRuntimeException {
        List results = null;
        try {
          Session session = DBSessionMgr.getDBReadSession();
          results = session.createQuery("FROM " + classToLoad.getName()).list();
          DBSessionMgr.closeDBReadSession(session);
        } catch (HibernateException e) {
            LOG.fatal( "Exception while searching all objects from POJO class: "+classToLoad.getName()+".", e );
          throw new DBRuntimeException(e);
        } catch (DBSessionException e) {
          LOG.error("Problem while searching all objects from POJO class: "+classToLoad.getName()+".", e);
          throw new DBRuntimeException(e);
        }
        return results;
      }

}

DBSessionMgr.java:
Code:
package it.eng.hibernate.util.mgr;

import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.apache.log4j.Logger;

public class DBSessionMgr implements TransactionalResource {

    private static final Logger LOG = Logger.getLogger(DBSessionMgr.class.getName());

    private static ThreadLocal<Session> localSession = new ThreadLocal<Session>();

    private static ThreadLocal<Transaction> localTransaction = new ThreadLocal<Transaction>();

    private static SessionFactory sessionFactory;

    public synchronized void beginTransaction() throws TransactionException {

        if (sessionFactory == null) {
            throw new TransactionException("This transaction resource has not been initialized, please " + "initialize it first.");
        }
        if (localSession != null && localSession.get() != null) {
            LOG.info("Encountered a pending transaction, commiting it before starting a new one.");
            commitTransaction();
        }

        Session session;
        Transaction tx;
        try {
            session = sessionFactory.openSession();
            session.setFlushMode(FlushMode.AUTO);

            tx = session.beginTransaction();
        } catch (HibernateException e) {
            LOG.error("Could not initialize the persistence.", e);
            throw new TransactionException(e);
        }

        localSession.set(session);
        localTransaction.set(tx);
        LOG.info("Beginning transaction with thread : " + Thread.currentThread() + " and session " + session);
    }

    public void initialize() throws TransactionException {

        if (sessionFactory == null) {
            try {
                sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (HibernateException e) {
                LOG.error("Could not initialize or configure the persistence factory.", e);
                throw new TransactionException(e);
            }
        }
    }


    public synchronized void commitTransaction() throws TransactionException {

        Transaction tx = localTransaction.get();
        Session session = localSession.get();
        try {
            tx.commit();
        } catch (HibernateException e) {
            LOG.error("Error closing the persistence when commiting.", e);
            rollbackTransaction();
            throw new TransactionException(e);
        } finally {
            try {
                session.close();
            } catch (HibernateException e) {
                LOG.fatal("Session could not be closed !!!", e);
            }
            localSession.set(null);
            localTransaction.set(null);
        }
        LOG.info("Commiting transaction with thread : " + Thread.currentThread());

    }

    public synchronized void rollbackTransaction() throws TransactionException {

        Transaction tx = localTransaction.get();
        Session session = localSession.get();
        if (tx != null) {
            try {
                tx.rollback();
            } catch (HibernateException he) {
                LOG.error("Exception while rollbacking", he);
                throw new TransactionException(he);
            } finally {
                if (session != null) {

                    try {
                        session.close();
                    } catch (HibernateException he) {

                        LOG.fatal("Cannot close session");
                        throw new TransactionException(he);
                    }
                }
            }
        }
        LOG.info("Rollbacking transaction with thread : " + Thread.currentThread());
    }

    public synchronized boolean hasTransaction() {

        if (localSession == null || localSession.get() == null) {
            return false;
        }
        if (localTransaction == null || localTransaction.get() == null) {
            return false;
        }
        return true;
    }

    public synchronized static Session getActiveSession() throws DBSessionException {
        if (localSession == null)
            throw new DBSessionException("No active persistence, the transaction has probably not been initialized " + "in thread " + Thread.currentThread());
        Session session = localSession.get();
        if (session == null) {
            throw new DBSessionException("No active persistence, the transaction has probably not been initialized " + "in thread " + Thread.currentThread());
        }
        return session;
    }

    public static Session getDBReadSession() throws DBSessionException {
        Session session = null;
        try {
            session = sessionFactory.openSession();
        } catch (HibernateException e) {
            throw new DBSessionException("Error");
        }
        return session;
    }

    public static void closeDBReadSession(Session session) throws DBSessionException {
        try {
            session.close();
        } catch (HibernateException e) {
            throw new DBSessionException("Error");
        }
    }
}

TestInserimento.java:
Code:
package test;

import java.util.Set;
import java.util.HashSet;

import it.eng.hibernate.util.db.Menu;
import it.eng.hibernate.util.db.SottoMenu;
import it.eng.hibernate.util.mgr.DBRuntimeException;
import it.eng.hibernate.util.mgr.DBSessionMgr;
import it.eng.hibernate.util.mgr.PersistentDataAccess;
import it.eng.hibernate.util.mgr.TransactionException;

import org.apache.log4j.Logger;


public class TestInserimento {
   
    private static final Logger LOG = Logger.getLogger( TestInserimento.class.getName() );
   
    public static void main( String[] args ){
       
        DBSessionMgr dbMgr = new DBSessionMgr();
        try {
            dbMgr.initialize();
            dbMgr.beginTransaction();
        } catch (TransactionException e1) {
            // TODO Auto-generated catch block
           LOG.error( "Errror in initialization", e1 );
        }
        Menu theMenu = new Menu();

        theMenu.setNome( "Test" );
        //theMenu.setId( 11 );
        theMenu.setNomePagina("PaginaTest");
        SottoMenu stMenu = new SottoMenu();

        stMenu.setMenu(theMenu);
        stMenu.setNome( "TestSottoMenu" );
        stMenu.setNomePagina( "SottoMenuTestPagina" );
        Set<SottoMenu> theStMenues = new HashSet<SottoMenu>();
        theStMenues.add( stMenu );
        theMenu.setSottoMenus( theStMenues );
        //theMenu.getSottoMenus().add(stMenu);
        try {
            PersistentDataAccess.create(theMenu);
            dbMgr.commitTransaction();
        } catch (DBRuntimeException e) {
            // TODO Auto-generated catch block
            LOG.error( "Errror in creating obj", e );
        } catch (Exception e) {
            // TODO: handle exception
           
            LOG.error( "Error in committing transaction obj", e );
        }
       
    }
}


Well by launching TestInserimento.java i have this result:

23:56:01,343 INFO [Environment] Hibernate 3.1.3
23:56:01,359 INFO [Environment] hibernate.properties not found
23:56:01,359 INFO [Environment] using CGLIB reflection optimizer
23:56:01,359 INFO [Environment] using JDK 1.4 java.sql.Timestamp handling
23:56:01,421 INFO [Configuration] configuring from resource: /hibernate.cfg.xml
23:56:01,421 INFO [Configuration] Configuration resource: /hibernate.cfg.xml
23:56:01,515 INFO [Configuration] Reading mappings from resource: hibernate/mapping/Servizi.hbm.xml
23:56:01,625 INFO [HbmBinder] Mapping class: it.eng.hibernate.util.db.Servizi -> servizi
23:56:01,640 INFO [Configuration] Reading mappings from resource: hibernate/mapping/Menu.hbm.xml
23:56:01,687 INFO [HbmBinder] Mapping class: it.eng.hibernate.util.db.Menu -> menu
23:56:01,687 INFO [Configuration] Reading mappings from resource: hibernate/mapping/Img.hbm.xml
23:56:01,734 INFO [HbmBinder] Mapping class: it.eng.hibernate.util.db.Img -> img
23:56:01,796 INFO [Configuration] Reading mappings from resource: hibernate/mapping/SottoMenu.hbm.xml
23:56:01,843 INFO [HbmBinder] Mapping class: it.eng.hibernate.util.db.SottoMenu -> sotto_menu
23:56:01,843 INFO [Configuration] Reading mappings from resource: hibernate/mapping/Contatti.hbm.xml
23:56:01,859 INFO [HbmBinder] Mapping class: it.eng.hibernate.util.db.Contatti -> contatti
23:56:01,859 INFO [Configuration] Reading mappings from resource: hibernate/mapping/Prodotto.hbm.xml
23:56:01,875 INFO [HbmBinder] Mapping class: it.eng.hibernate.util.db.Prodotto -> prodotto
23:56:01,875 INFO [Configuration] Configured SessionFactory: galleria
23:56:01,875 INFO [HbmBinder] Mapping collection: it.eng.hibernate.util.db.Menu.sottoMenus -> sotto_menu
23:56:01,875 INFO [HbmBinder] Mapping collection: it.eng.hibernate.util.db.Prodotto.imgs -> img
23:56:01,921 INFO [DriverManagerConnectionProvider] Using Hibernate built-in connection pool (not for production use!)
23:56:01,921 INFO [DriverManagerConnectionProvider] Hibernate connection pool size: 20
23:56:01,921 INFO [DriverManagerConnectionProvider] autocommit mode: false
23:56:01,953 INFO [DriverManagerConnectionProvider] using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/galleriacorso
23:56:01,953 INFO [DriverManagerConnectionProvider] connection properties: {user=root, password=****}
23:56:02,484 INFO [SettingsFactory] RDBMS: MySQL, version: 5.0.19-nt
23:56:02,484 INFO [SettingsFactory] JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-3.1.12 ( $Date: 2005-11-17 15:53:48 +0100 (Thu, 17 Nov 2005) $, $Revision$ )
23:56:02,515 INFO [Dialect] Using dialect: org.hibernate.dialect.MySQLDialect
23:56:02,515 INFO [TransactionFactoryFactory] Using default transaction strategy (direct JDBC transactions)
23:56:02,515 INFO [TransactionManagerLookupFactory] No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
23:56:02,515 INFO [SettingsFactory] Automatic flush during beforeCompletion(): disabled
23:56:02,515 INFO [SettingsFactory] Automatic session close at end of transaction: disabled
23:56:02,515 INFO [SettingsFactory] JDBC batch size: 15
23:56:02,515 INFO [SettingsFactory] JDBC batch updates for versioned data: disabled
23:56:02,515 INFO [SettingsFactory] Scrollable result sets: enabled
23:56:02,515 INFO [SettingsFactory] JDBC3 getGeneratedKeys(): enabled
23:56:02,515 INFO [SettingsFactory] Connection release mode: auto
23:56:02,546 INFO [SettingsFactory] Maximum outer join fetch depth: 2
23:56:02,546 INFO [SettingsFactory] Default batch fetch size: 1
23:56:02,546 INFO [SettingsFactory] Generate SQL with comments: disabled
23:56:02,546 INFO [SettingsFactory] Order SQL updates by primary key: disabled
23:56:02,546 INFO [SettingsFactory] Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
23:56:02,546 INFO [ASTQueryTranslatorFactory] Using ASTQueryTranslatorFactory
23:56:02,546 INFO [SettingsFactory] Query language substitutions: {}
23:56:02,546 INFO [SettingsFactory] Second-level cache: enabled
23:56:02,546 INFO [SettingsFactory] Query cache: disabled
23:56:02,546 INFO [SettingsFactory] Cache provider: org.hibernate.cache.EhCacheProvider
23:56:02,546 INFO [SettingsFactory] Optimize cache for minimal puts: disabled
23:56:02,546 INFO [SettingsFactory] Structured second-level cache entries: disabled
23:56:02,546 INFO [SettingsFactory] Statistics: disabled
23:56:02,546 INFO [SettingsFactory] Deleted entity synthetic identifier rollback: disabled
23:56:02,546 INFO [SettingsFactory] Default entity-mode: pojo
23:56:02,562 INFO [SessionFactoryImpl] building session factory
23:56:02,562 DEBUG [CacheManager] Creating new CacheManager with default config
23:56:02,578 DEBUG [CacheManager] Configuring ehcache from classpath.
23:56:02,578 WARN [Configurator] No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Documents%20and%20Settings/Angelo/workspace/GalleriaCorsoDB/libs/ehcache-1.1.jar!/ehcache-failsafe.xml
23:56:02,578 DEBUG [Configuration$DiskStore] Disk Store Path: C:\DOCUME~1\Angelo\IMPOST~1\Temp\
23:56:03,125 INFO [SessionFactoryObjectFactory] Factory name: galleria
23:56:03,125 INFO [NamingHelper] JNDI InitialContext properties:{}
23:56:03,140 WARN [SessionFactoryObjectFactory] Could not bind factory to JNDI
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:284)
at javax.naming.InitialContext.getNameParser(InitialContext.java:439)
at org.hibernate.util.NamingHelper.bind(NamingHelper.java:52)
at org.hibernate.impl.SessionFactoryObjectFactory.addInstance(SessionFactoryObjectFactory.java:90)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:291)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1176)
at it.eng.hibernate.util.mgr.DBSessionMgr.initialize(DBSessionMgr.java:52)
at test.TestInserimento.main(TestInserimento.java:24)
23:56:03,171 INFO [DBSessionMgr] Beginning transaction with thread : Thread[main,5,main] and session SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
23:56:03,375 INFO [DBSessionMgr] Commiting transaction with thread : Thread[main,5,main]


I have only a warning but no Exception. But the result is that there is an insert only on table Menu, SottoMenu has no record...of course i'm wrong in some step can anybody explain to me how i must configure hibernate in order to persist also collections?
Thanks to all


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 24, 2006 6:32 pm 
Expert
Expert

Joined: Thu Sep 22, 2005 10:29 am
Posts: 285
Location: Almassera/Valencia/Spain/EU/Earth/Solar system/Milky Way/Local Group/Virgo Supercluster
try changing Menu mapping to
Code:
<set name="sottoMenus" inverse="true" cascade="all">


also read
Chapter 21. Example: Parent/Child
of the Hibernate reference

Also
You are using
Code:
<id name="id" type="int">
   <column name="ID" />
   <generator class="assigned" />
</id>

but you don't use setId(int id) method
I suppose it shouldn't works right.


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 24, 2006 6:39 pm 
Regular
Regular

Joined: Mon May 22, 2006 2:30 pm
Posts: 74
Hibernate does not automatically cascade the insertions to include the collection. You need to modify the mapping for Menu so that the line which refers to the SottoMenu collection provides a value for the cascade property, as follows:

<set name="sottoMenus" inverse="true" cascade="save-update">

There are several options for cascade. This one will cascades saves and updates, but not deletes. If you don't set the cascade, you have to iterate thru the collection by hand and call session.save() on each persistent object in the collection.


Top
 Profile  
 
 Post subject:
PostPosted: Thu May 25, 2006 7:16 am 
Newbie

Joined: Wed May 24, 2006 5:47 pm
Posts: 14
Thanks to all for your help.
I'll try to modify my mapping files as soon as possible.
Have a good day.
Angelo


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.