-->
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.  [ 8 posts ] 
Author Message
 Post subject: can't save
PostPosted: Fri May 04, 2007 4:26 pm 
Newbie

Joined: Thu Nov 23, 2006 1:46 am
Posts: 8
Location: Brussels
Problems with Session and transaction handling?

Read this: http://hibernate.org/42.html

Hello every one

i use hibernate 3.2
HSQLDB standalone


I have a problem saving to the database HSQLDB standalone
I can do the other operation (get , delete, update) but i can't save new instance to the database..

if i run the code i don't get any error, nothing happens and no exception thrown

i tried assigned key and native key generators
but both give the save problem

any idea?



Mapping file
Code:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="model.beans.Rooster" table="ROOSTERS" schema="PUBLIC">
        <id name="roosterId" type="java.lang.Long">
            <column name="ROOSTER_ID" />
            <generator class="assigned"></generator>
        </id>
        <property name="fieldNum" type="java.lang.Integer">
           <column name="FIELDNUM" not-null="false"></column>
        </property>
        <property name="dayNum" type="java.lang.Integer">
            <column name="DAY_NUM" not-null="true" />
        </property>
        <property name="startTime" type="java.util.Calendar">
            <column name="START_TIME" length="6" not-null="true" />
        </property>
        <property name="endTime" type="java.util.Calendar">
            <column name="END_TIME" length="6" not-null="true" />
        </property>
        <set name="matchPlannings" inverse="true">
            <key>
                <column name="FK_ROOSTERID" />
            </key>
            <one-to-many class="model.beans.MatchPlanning" />
        </set>
    </class>
</hibernate-mapping>



the save method in the dao class
Code:
   public void saveOrUpdate(Rooster obj) {
      
       log.debug("saving Roosters instance");
           try {
              HibernateSessionFactory.getSession().saveOrUpdate(obj);
              System.out.println("Saving rooster with id"+obj.getRoosterId() + " ok");
               log.debug("save successful");
           } catch (RuntimeException re) {
               log.error("save failed", re);
               throw re;
           }
   }


session factory
Code:
package model.beans;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution.  Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses 
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
   private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    private HibernateSessionFactory() {
    }
   
   /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

      if (session == null || !session.isOpen()) {
         if (sessionFactory == null) {
            rebuildSessionFactory();
         }
         session = (sessionFactory != null) ? sessionFactory.openSession()
               : null;
         threadLocal.set(session);
      }

        return session;
    }

   /**
     *  Rebuild hibernate session factory
     *
     */
   public static void rebuildSessionFactory() {
      try {
         configuration.configure(configFile);
         sessionFactory = configuration.buildSessionFactory();
      } catch (Exception e) {
         System.err
               .println("%%%% Error Creating SessionFactory %%%%");
         e.printStackTrace();
      }
   }

   /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

   /**
     *  return session factory
     *
     */
   public static org.hibernate.SessionFactory getSessionFactory() {
      return sessionFactory;
   }

   /**
     *  return session factory
     *
     *   session factory will be rebuilded in the next call
     */
   public static void setConfigFile(String configFile) {
      HibernateSessionFactory.configFile = configFile;
      sessionFactory = null;
   }

   /**
     *  return hibernate configuration
     *
     */
   public static Configuration getConfiguration() {
      return configuration;
   }

}


Top
 Profile  
 
 Post subject:
PostPosted: Fri May 04, 2007 4:32 pm 
Expert
Expert

Joined: Tue Jul 11, 2006 10:21 am
Posts: 457
Location: Columbus, Ohio
I don't see any transaction handling. Is that somewhere else?

Also, you minght want to check out contextual session management in the reference, it's a lot easier than implementing your own ThreadLocal session handlers.


Top
 Profile  
 
 Post subject:
PostPosted: Fri May 04, 2007 4:38 pm 
Expert
Expert

Joined: Tue Jul 11, 2006 10:21 am
Posts: 457
Location: Columbus, Ohio
Oops, you are using saveOrUpdate() with an assigned id.

Reference manual wrote:
saveOrUpdate() does the following:
• if the object is already persistent in this session, do nothing
• if another object associated with the session has the same identifier, throw an exception
• if the object has no identifier property, save() it
• if the object's identifier has the value assigned to a newly instantiated object, save() it
• if the object is versioned (by a <version> or <timestamp>), and the version property value is the same
value assigned to a newly instantiated object, save() it
• otherwise update() the object


Hibernate has no way of determining if the object is transient or persistent, so I don't think saveOrUpdate() will function as you think it will, it will attempt to update() it instead of save() it.


Top
 Profile  
 
 Post subject:
PostPosted: Sat May 05, 2007 1:03 am 
Newbie

Joined: Thu Nov 23, 2006 1:46 am
Posts: 8
Location: Brussels
thx Ananasi
but i was searching to know how can i use the JTASessionContext class

what i did is i added the property

Code:
<property name="hibernate.current_session_context_class">
      jta
   </property>


to hibernate.cfg.xml

but how can i get a session using JTASessionContext class?
do i have to extend this class

the constructor is protected?

any idea

thx


Top
 Profile  
 
 Post subject:
PostPosted: Sat May 05, 2007 1:07 am 
Newbie

Joined: Thu Nov 23, 2006 1:46 am
Posts: 8
Location: Brussels
correction
i changed the property to

Code:

<property name="hibernate.current_session_context_class">
      org.hibernate.context.JTASessionContext
   </property>


Forgot to say that this is a stand a lone application

thx


Top
 Profile  
 
 Post subject:
PostPosted: Sat May 05, 2007 10:02 am 
Newbie

Joined: Tue Mar 27, 2007 12:42 pm
Posts: 5
hi,
if you're handling transactions on your own and want your entities persisted immediatley, try something like this:

Code:
Transaction tx = session.beginTransaction();
try {
   session.save( entity );
   session.flush();
   tx.commit();
}
catch(HibernateException e) {
   tx.rollback();
   // log || handle exception
}



gruss,
chris


Top
 Profile  
 
 Post subject:
PostPosted: Mon May 07, 2007 8:11 am 
Expert
Expert

Joined: Tue Jul 11, 2006 10:21 am
Posts: 457
Location: Columbus, Ohio
mike009 wrote:
but how can i get a session using JTASessionContext class?
do i have to extend this class


Ah, the beauty of the contextual sessions is that all you have to do is start your JTA transaction, and sessionFactory.getCurrentSession() will return the Hibernate session associated with that JTA transaction. As long as the JTA transaction is still pending, every call to getCurrentSession() will return the same session that is associated with the transaction.

Of course, using JTA transactions in a standalone application is not something I have ever done (web app developer), but if it works for you...


Top
 Profile  
 
 Post subject: Set autocommit
PostPosted: Mon Dec 31, 2007 4:03 pm 
Newbie

Joined: Mon Dec 31, 2007 3:57 pm
Posts: 1
If you are not explicitely adding transactions to your queries, then try setting your autocommit property in the hibernate.cfg.xml file.

<property name="connection.autocommit">true</property>

It is very possible that you problem is that the commit command never gets called because you are not running transactions. This property will force the commit.

_________________
Brian Nettles
Trisummit Technologies, Inc.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 8 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.