facebook

Hibernate not committing [Closed]

  1. MyEclipse IDE
  2.  > 
  3. General Development
Viewing 15 posts - 1 through 15 (of 17 total)
  • Author
    Posts
  • #215118 Reply

    I ran into a problem where my updates seemed to work in my website, but were not available when I looked at my data in sqlplus (I’m using oracle).

    In my TableService class which was generated using the Hibernate wizard, the updateTable method had the following code:

    
    session.flush();
    

    I added the following code:

    
    session.connection().commit();
    

    and that fixed the problem. However, as this is generated code, I’d prefer to not have to put that change in. Is there something I’m missing, some configuration option in the hibernate.properties perhaps?

    Lee

    #215130 Reply

    Riyad Kalla
    Member

    Lee let me check with Jeff on this, thank you for the code.

    #215135 Reply

    support-jeff
    Member

    Lee –

    Can you post the full code? There is no call to flush() in the velocity templates that we ship with 3.8.1. Therefore, it must be in your code. However, I would be happy to take a look.

    #215160 Reply

    peterwontner
    Member

    From your code snippet, you are accessing the conenction from the session and calling commit() directly. Are you providing the Connection to the Hibernate session or are you letting Hibernate manage your connections? I ask because if you are letting Hibernate manage the connections, then you just need to call commit() on the session object.
    Hibernate employs a write-behind mechanism, where data is only persisted to the database when commit is called.

    #215161 Reply

    Here’s my code. The only thing I added was the commit line, everthing else was genertated by the hibernate wizard.

    
        public void updateDataStore(DataStore DataStore)
        {
            /*
             * Use the ConnectionFactory to retrieve an open
             * Hibernate Session.
             * 
             */
            Session session = ConnectionFactory.getInstance().getSession();
    
            try
            {
                /*
                 * Update the state of the DataStore using the Hibernate session's update method.
                 * 
                 * Call the flush method to ensure that the object in saved.
                 * 
                 */
                session.update(DataStore);
                session.flush();
                session.connection().commit();
            }
            catch (HibernateException e)
            {
                log.error("Hibernate Exception" + e.getMessage());
                throw new RuntimeException(e);
            }
            catch (Exception e)
            {
                log.error("NonHibernate Exception" + e.getMessage());
                throw new RuntimeException(e);
            }
          /*
           * Regardless of whether the above processing resulted in an Exception
           * or proceeded normally, we want to close the Hibernate session.  When
           * closing the session, we must allow for the possibility of a Hibernate
           * Exception.
           * 
           */
            finally
            {
                if (session != null)
                {
                    try
                    {
                        session.close();
                    }
                    catch (HibernateException e)
                    {
                        log.error("Hibernate Exception" + e.getMessage());
                        throw new RuntimeException(e);
                    }
    
                }
            }
    
        }
    
    #215162 Reply

    @peterwontner wrote:

    From your code snippet, you are accessing the conenction from the session and calling commit() directly. Are you providing the Connection to the Hibernate session or are you letting Hibernate manage your connections? I ask because if you are letting Hibernate manage the connections, then you just need to call commit() on the session object.
    Hibernate employs a write-behind mechanism, where data is only persisted to the database when commit is called.

    Here’s the code that’s in my action class that calls the “updateMyTable” in the “MyTableService” class that was generated by the hibernate wizard. The update appears on the web app — but didn’t appear when I used sql plus. Thus I knew that the commit never occurred. Adding the commit to the “updateMyTable” fixed the problem. I just wanted to avoid having to add this fix everytime I ran the generator.

    
        private void dataStoreUpdate(HttpServletRequest request) throws Exception {
    
            // Get blank instance of dataStore
            DataStore dataStore = new DataStore();
            
            // Get the dataStoreForm instance from the request scope
            DataStoreForm dataStoreForm = (DataStoreForm) request.getAttribute("dataStoreForm");
    
            // Copy the values from dataStoreForm to dataStore
            BeanUtils.copyProperties(dataStore,dataStoreForm);
    
            // Set LastModBy and LastModDate
            dataStore.setLastModBy("LoginUser");
            Calendar cal = Calendar.getInstance(TimeZone.getDefault());    
            dataStore.setLastModDate(cal.getTime());
            
            // Save the values to the database
            DataStoreService.getInstance().updateDataStore(dataStore);
    
        }
    

    Lee

    #215172 Reply

    snpe
    Member

    You mix JDBC and hibernate
    For hibernate transaction You have to use Trasnaction object from hibernate
    See CaveatEmptor (caveatemptor.hibernate.org) – class HibernateUtil and reference documentation

    regards

    #215173 Reply

    @snpe wrote:

    You mix JDBC and hibernate
    For hibernate transaction You have to use Trasnaction object from hibernate
    See CaveatEmptor (caveatemptor.hibernate.org) – class HibernateUtil and reference documentation

    I’m not sure what you mean. I’m using the code generated by the hibernate wizard. It doesn’t commit the data to the database. Adding a commit statement to it solved the problem.

    Either the generated code should inlcude a commit statement, or there is some configuration switch I don’t know about that will accomplish the task.

    What I’m suggesting is that the hibernate wizard code is rather useless if it doesn’t commit the data to the database. Now I realize that I might not understand how to properly set things up.

    Lee

    #215185 Reply

    snpe
    Member

    I don’t use hibernate wizard, but if exits command
    session.connection().commit();
    its isn’t good
    Transaction in hibernate is like :

    Session session = sessionFactory.openSession();
    Transaction tx = null;

    try {
    tx.beginTrasnaction();
    // your command : save,saveOrCopy etc
    tx.commit()
    } catch (Exception e)
    if (tx != null)
    try {
    tx.rollback();
    } catch (HibernateException e) {
    // throw any exception
    }
    throw e;
    } finally {
    try {
    session.close();
    } catch (Exception e) {
    throw e;
    }
    }

    It is better use spring AOP transaction managment

    regards

    #215186 Reply

    I think you are not understanding something — I have the code working. But in order to do that, I had to change the generated code. I would hope that the hibernate generator would generate code that either doesn’t need a commit, or generates the commit. I’m sure it’s quite possible that there’s something I’m missing here.

    #215193 Reply

    snpe
    Member

    Maybe Your code work, but wtht trasnaction You don’t sure – concurent access is accidently
    if You mix jdbc and hibernate transaction processing you will have troubles , probably

    regards

    #215197 Reply

    peterwontner
    Member

    I have used the ME Hibernate Wizard for a few projects, and I have not seen code like the one you give as an example. Is it possible that you could be using something like Hibernator or Hibernate Synchronizer?

    How did you invoke the Hibernate Wizard?

    I think what snpe was referring to is that fact that you are not wrapping your updates in Hibernate (or any) transactions. The code sample that snpe provides is generally the correct approach to persisting data using Hibernate. You should also not need to obtain the Connection directly to do the commit, but call session.commit().

    I would recommend purchasing the new Hibernate In Action book. This is an excellent book written by the people who created Hibernate.

    #215200 Reply

    @peterwontner wrote:

    I have used the ME Hibernate Wizard for a few projects, and I have not seen code like the one you give as an example. Is it possible that you could be using something like Hibernator or Hibernate Synchronizer?

    I’ve never downloaded and installed those products. I installed a clean Eclipse and a clean MyEclipse. I am up to 3.8.1 quick fix 3

    I use the database explorer, navigate to my table, right click, then “Generate Hibernate Mapping”

    @peterwontner wrote:

    I think what snpe was referring to is that fact that you are not wrapping your updates in Hibernate (or any) transactions.

    Right, and I’m saying the following: I did not code the hibernate code in question. I used the generator that I got from MyEclipse — though you have cast doubt on that, but I don’t know how I’d have gotten any other generator.

    Therefore — I’m asking “why is the MyEclipse code being generated without committing the data”.

    And now, I guess, there seems to be some question as to whether or not I’m actually running MyEclipses’ code generator.

    @peterwontner wrote:

    I would recommend purchasing the new Hibernate In Action book. This is an excellent book written by the people who created Hibernate.

    Yes, I could write the code myself. However, you guys include the hibernate code generator with MyEclipse. If you don’t — and I’m mistaken, my apologies.

    If you do — and the code that’s being generated is wrong, then I’d like to fix it. Either by you fixing it, or by know where I need to go to change the code generation.

    Lee

    #215201 Reply

    Ok…here’s a new file freshly generated, and not touched by me. The table’s name is “item”. I went to the _MyEclipse_ Database Explorer, right clicked on the items table and chose to Generate Hibernate Mapping — in addition to Item.hbm.xml, it created Item.java, AbstractItem.Java, and ItemServices

    Below is the code for the ItemServices.java

    
    /*
     * Created on Sep 8, 2004
     *
     * TODO To change the template for this generated file go to
     * Window - Preferences - Java - Code Style - Code Templates
     */
    package com.sbc.netrics.struts.database;
    /*
     * Created on Nov 26, 2003
     *
     * To change the template for this generated file go to
     * Window>Preferences>Java>Code Generation>Code and Comments
     */
    
    import java.util.List;
    
    import net.sf.hibernate.HibernateException;
    import net.sf.hibernate.ObjectNotFoundException;
    import net.sf.hibernate.Query;
    import net.sf.hibernate.Session;
    
    /**
     * Provides an interface used to access <code>Item</code> objects from the 
     * database using Hibernate.
     * 
     * Copyright 2003 Edward Hand
     * 
     * @author Edward Hand
     *
     */
    /*
     * The ItemService class uses the Singleton design pattern to provide an interface 
     * to the Struts application allowing it to work with Item objects through 
     * the persistence layer.
     * 
     * No Hibernate-related code exists above this layer.  This would allow us, in the
     * future, to switch to some other method of object persistence without making changes
     * to the Struts-related code in the application.
     *  
     */
    public class ItemService
    {
    
        private static ItemService instance = null;
    
        private ItemService()
        {
    
        }
    
        /**
         * getInstance() returns the instance of the <code>ItemService</code> singleton.
         * 
         * @return <code>ItemService</code> singleton.
         */
        public static synchronized ItemService getInstance()
        {
            /*
             * Creates the Singleton instance, if needed.
             * 
             */
            if (instance == null)
            {
                instance = new ItemService();
            }
            return instance;
        }
    
        /**
         * getItem() returns <code>Item</code> object from database with given id.  If
         * the user is not found, will return null.
         * 
         * @param id The <code>Long</code> id of desired <code>Item</code> 
         * @return <code>Item</code> with given id, if it exists.  Otherwise, returns null.
         */
        public Item getItem(Long id)
        {
    
            /*
             * Use the ConnectionFactory to retrieve an open
             * Hibernate Session.
             * 
             */
            Session session = ConnectionFactory.getInstance().getSession();
    
            try
            {
                /*
                 * Calls the load method on the Hibernate session object
                 * to retrieve the Item with the provided id.
                 */
                return (Item) session.load(Item.class, id);
            }
            /*
             * If the object is not found, i.e., no Item exists with the
             * requested id, we want the method to return null rather 
             * than throwing an Exception.
             * 
             */
            catch (ObjectNotFoundException onfe)
            {
                return null;
            }
            catch (HibernateException e)
            {
                /*
                 * All Hibernate Exceptions are transformed into an unchecked
                 * RuntimeException.  This will have the effect of causing the
                 * user's request to return an error.
                 * 
                 */
                System.err.println("Hibernate Exception" + e.getMessage());
                throw new RuntimeException(e);
            }
            /*
             * Regardless of whether the above processing resulted in an Exception
             * or proceeded normally, we want to close the Hibernate session.  When
             * closing the session, we must allow for the possibility of a Hibernate
             * Exception.
             * 
             */
            finally
            {
                if (session != null)
                {
                    try
                    {
                        session.close();
                    }
                    catch (HibernateException e)
                    {
                        System.err.println("Hibernate Exception" + e.getMessage());
                        throw new RuntimeException(e);
                    }
    
                }
            }
    
        }
    
        /** 
         * updateItem() updates specfied <code>Item</code> through Hibernate.
         * 
         * @param item An <code>Item</code> to be updated
         */
        public void updateItem(Item item)
        {
            /*
             * Use the ConnectionFactory to retrieve an open
             * Hibernate Session.
             * 
             */
            Session session = ConnectionFactory.getInstance().getSession();
    
            try
            {
                /*
                 * Update the state of the item using the Hibernate session's update method.
                 * 
                 * Call the flush method to ensure that the object in saved.
                 * 
                 */
                session.update(item);
                session.flush();
            }
            catch (HibernateException e)
            {
                System.err.println("Hibernate Exception" + e.getMessage());
                throw new RuntimeException(e);
            }
          /*
           * Regardless of whether the above processing resulted in an Exception
           * or proceeded normally, we want to close the Hibernate session.  When
           * closing the session, we must allow for the possibility of a Hibernate
           * Exception.
           * 
           */
            finally
            {
                if (session != null)
                {
                    try
                    {
                        session.close();
                    }
                    catch (HibernateException e)
                    {
                        System.err.println("Hibernate Exception" + e.getMessage());
                        throw new RuntimeException(e);
                    }
    
                }
            }
    
        }
    
        /**
         * getItemList() returns list of all <code>Item</code> objects stored in the database. 
         * 
         * @return <code>List</code> of <code>Item</code> objects.
         */
        public List getItemList()
        {
            /*
             * Use the ConnectionFactory to retrieve an open
             * Hibernate Session.
             * 
             */
            Session session = ConnectionFactory.getInstance().getSession();
    
            try
            {
                /*
                * Build HQL (Hibernate Query Language) query to retrieve a list
                * of all the items currently stored by Hibernate.
                 */
                Query query =
                    session.createQuery(
                        "select item from com.sbc.netrics.struts.database.Item item order by item.name");
                return query.list();
    
            }
            catch (HibernateException e)
            {
                System.err.println("Hibernate Exception" + e.getMessage());
                throw new RuntimeException(e);
            }
            /*
             * Regardless of whether the above processing resulted in an Exception
             * or proceeded normally, we want to close the Hibernate session.  When
             * closing the session, we must allow for the possibility of a Hibernate
             * Exception.
             * 
             */
            finally
            {
                if (session != null)
                {
                    try
                    {
                        session.close();
                    }
                    catch (HibernateException e)
                    {
                        System.err.println("Hibernate Exception" + e.getMessage());
                        throw new RuntimeException(e);
                    }
    
                }
            }
        }
    
        /**
         * addItem() inserts new <code>Item</code> into the database through Hibernate.
         * 
         * @param item A new <code>Item</code> to be added.
         */
        public void addItem(Item item)
        {
    
            Session session = ConnectionFactory.getInstance().getSession();
    
            try
            {
                session.save(item);
                session.flush();
            }
            catch (HibernateException e)
            {
                System.err.println("Hibernate Exception" + e.getMessage());
                throw new RuntimeException(e);
            }
            /*
             * Regardless of whether the above processing resulted in an Exception
             * or proceeded normally, we want to close the Hibernate session.  When
             * closing the session, we must allow for the possibility of a Hibernate
             * Exception.
             * 
             */
            finally
            {
                if (session != null)
                {
                    try
                    {
    
                        session.close();
                    }
                    catch (HibernateException e)
                    {
                        System.err.println("Hibernate Exception" + e.getMessage());
                        throw new RuntimeException(e);
                    }
    
                }
            }
    
        }
    
    }
    

    Lee

    #215204 Reply

    I’m an idiot — <MyTable>Service isn’t automatically generated

    <sigh>

    Sorry for disturbing the board. I got that code example from another website, and confused myself, thinking it was one of the generated files.

    boot to the head for me.

    Lee

Viewing 15 posts - 1 through 15 (of 17 total)
Reply To: Hibernate not committing [Closed]

You must be logged in to post in the forum log in