-->
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: Hibernate 3 unable to update or delete
PostPosted: Wed May 11, 2005 10:57 am 
Regular
Regular

Joined: Wed Sep 29, 2004 11:34 am
Posts: 62
Location: Houston, TX
Migrating from Hibernate 2 to Hibernate 3. I have almost completed the migration but after some testing I found out that I am unable to update or delete. Oddly enough I can save, but I don't seem to know why I cannot update or delete.

I tried to see if any errors occured, but none that were visible. It seems to complete the call but nothing gets updated or deleted in the database.

After a lot of testing to see where the error might be, I think I found it but not sure. I am using JBoss so I am packaging my hibernate stuff in a HAR file. When I look at the log when JBoss starts up and Hibernate initializes I see the following:

09:27:15,309 INFO [Configuration] processing association property references
09:27:15,309 INFO [Configuration] processing foreign key constraints
09:27:15,387 INFO [Dialect] Using dialect: org.hibernate.dialect.MySQLDialect
09:27:15,402 INFO [SettingsFactory] Maximum outer join fetch depth: 2
09:27:15,402 INFO [SettingsFactory] Default batch fetch size: 1
09:27:15,402 INFO [SettingsFactory] Generate SQL with comments: disabled
09:27:15,402 INFO [SettingsFactory] Order SQL updates by primary key: disabled
09:27:15,402 INFO [SettingsFactory] Query translator: org.hibernate.hql.ast.AST
QueryTranslatorFactory
09:27:15,418 INFO [ASTQueryTranslatorFactory] Using ASTQueryTranslatorFactory
09:27:15,418 INFO [SettingsFactory] Query language substitutions: {}
09:27:15,434 INFO [NamingHelper] JNDI InitialContext properties:{}
09:27:15,434 INFO [DatasourceConnectionProvider] Using datasource: java:/MySqlD
S
09:27:15,746 INFO [SettingsFactory] JDBC batch size: 15
09:27:15,746 INFO [SettingsFactory] JDBC batch updates for versioned data: disa
bled
09:27:15,746 INFO [SettingsFactory] Scrollable result sets: enabled
09:27:15,746 INFO [SettingsFactory] JDBC3 getGeneratedKeys(): enabled
09:27:15,746 INFO [TransactionFactoryFactory] Transaction strategy: org.hiberna
te.transaction.JTATransactionFactory
09:27:15,746 INFO [NamingHelper] JNDI InitialContext properties:{}
09:27:15,746 INFO [TransactionManagerLookupFactory] instantiating TransactionMa
nagerLookup: org.hibernate.transaction.JBossTransactionManagerLookup
09:27:15,746 INFO [TransactionManagerLookupFactory] instantiated TransactionMan
agerLookup
09:27:15,762 INFO [TransactionManagerLookupFactory] instantiating TransactionMa
nagerLookup: org.hibernate.transaction.JBossTransactionManagerLookup
09:27:15,762 INFO [TransactionManagerLookupFactory] instantiated TransactionMan
agerLookup
09:27:15,762 INFO [SettingsFactory] Automatic flush during beforeCompletion():
enabled
09:27:15,762 INFO [SettingsFactory] Automatic session close at end of transacti
on: enabled
09:27:15,762 INFO [SettingsFactory] Cache provider: org.hibernate.cache.TreeCac
heProvider
09:27:15,762 INFO [SettingsFactory] Second-level cache: enabled
09:27:15,762 INFO [SettingsFactory] Optimize cache for minimal puts: enabled
09:27:15,762 INFO [SettingsFactory] Structured second-level cache entries: enab
led
09:27:15,762 INFO [SettingsFactory] Query cache: disabled
09:27:15,762 INFO [SettingsFactory] Statistics: disabled
09:27:15,762 INFO [SettingsFactory] Deleted entity synthetic identifier rollbac
k: disabled

I presume the statement of "Order SQL updates by primary key: disabled" disables the update.


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 11, 2005 11:39 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 3:00 pm
Posts: 1816
Location: Austin, TX
No, it just means that the update statements will not be executed in the order of the primary keys to be updated.

Are you *certain* that your transaction commits?


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 11, 2005 11:47 am 
Regular
Regular

Joined: Wed Sep 29, 2004 11:34 am
Posts: 62
Location: Houston, TX
Steve I thought that would be the problem, but it seems to commit fine during the save mode, but why not during the update mode. I do not get an exception so I am not sure. I am trying to use the DAO methodology and implementing from Hibernate Synchronizer. I updated all the code that I thought needed updating. Below is how the updates happen.

Code:
protected static Map sessionFactoryMap = new HashMap();
    protected static ThreadLocal threadedSessions = new ThreadLocal();
    protected static ThreadLocal threadTransaction = new ThreadLocal();
    protected static ThreadLocal threadInterceptor = new ThreadLocal();
    private static Log log = LogFactory.getLog(_BaseRootDAO.class);

    /**
     * Return the SessionFactory that is to be used by these DAOs.  Change this
     * and implement your own strategy if you, for example, want to pull the SessionFactory
     * from the JNDI tree.
     */
    protected 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) {
            log.error(ex.getMessage());
            ex.printStackTrace();
        }
        return sessions;
    }


    /**
     * Return a new Session object that must be closed when the work has been completed.
     * @return the active Session
     */
    protected Session getSession() throws HibernateException {
        Session s = (Session) threadedSessions.get();
        try {
            if (s == null) {
                if (getInterceptor() != null) {
                    s = getSessionFactory().openSession(getInterceptor());
                } else {
                    s = getSessionFactory().openSession();
                }
                threadedSessions.set(s);
            }
        } catch (HibernateException ex) {
            log.error(ex.getMessage());
            throw ex;
        }
        return s;
    }

/**
     * Close the session
     */
    public void closeSession () throws HibernateException {
        try {
            Session s = (Session) threadedSessions.get();
            threadedSessions.set(null);
            if (s != null && s.isOpen()) {
                s.close();
            }
        } catch (HibernateException ex) {
            log.error(ex.getMessage());
            throw ex;
        }
    }

    /**
     * Start a new database transaction.
     */
    public void beginTransaction() throws HibernateException  {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            if (tx == null) {
                tx = getSession().beginTransaction();
                threadTransaction.set(tx);
            }
        } catch (HibernateException ex) {
            log.error(ex.getMessage());
            throw ex;
        }
    }

    /**
     * Commit the database transaction.
     */
    public void commitTransaction() throws HibernateException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            if ( tx != null && !tx.wasCommitted()
                            && !tx.wasRolledBack() ) {
                tx.commit();
            }
            threadTransaction.set(null);
        } catch (HibernateException ex) {
            ex.printStackTrace();
            rollbackTransaction();
            throw ex;
            //ex.printStackTrace();
        }
    }

    /**
     * Commit the database transaction.
     */
    public void rollbackTransaction() throws HibernateException {
        System.out.println("Starting RollBack");
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            threadTransaction.set(null);
            if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
                tx.rollback();
            }
        } catch (HibernateException ex) {
            log.error(ex.getMessage());
            throw ex;
        } finally {
            try {
                closeSession();
            }
            catch (HibernateException e){
                log.error(e.getMessage());
                throw e;
            }
        }
    }

     * Used by the base DAO classes but here for your modification
     * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
     * instance with the same identifier in the current session.
     * @param obj a transient instance containing updated state
     */
    protected void update(Object obj) throws HibernateException {
        Session s = null;
        try {
            s = getSession();
            beginTransaction();
            System.out.println("About to Update1 DAO");
            update(obj, s);
            commitTransaction();
        }
        catch (HibernateException e) {
            e.printStackTrace();
            this.rollbackTransaction();
            throw e;
        }
        finally {
            closeSession();
        }
    }

    /**
     * Used by the base DAO classes but here for your modification
     * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
     * instance with the same identifier in the current session.
     * @param obj a transient instance containing updated state
     * @param s the Session
     */
    protected void update(Object obj, Session s) throws HibernateException {
        System.out.println("About to Update2 inside DAO");
        s.update(obj);
    }

    /**
     * Used by the base DAO classes but here for your modification
     * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
     * Session or a transient instance with an identifier associated with existing persistent state.
     */
    protected void delete(Object obj) throws HibernateException {
        Session s = null;
        try {
            s = getSession();
            beginTransaction();
            System.out.println("About to delete1 inside DAO");
            delete(obj, s);
            commitTransaction();
        }
        catch (HibernateException e) {
            e.printStackTrace();
            this.rollbackTransaction();
            throw e;
        }
        finally {
            closeSession();
        }
    }

    /**
     * Used by the base DAO classes but here for your modification
     * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
     * Session or a transient instance with an identifier associated with existing persistent state.
     */
    protected void delete(Object obj, Session s) throws HibernateException {
        System.out.println("About to Delete2 inside DAO");
        try {
            s.delete(obj);
        }
        catch (Exception e) {e.printStackTrace();}
    }


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 11, 2005 11:52 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 3:00 pm
Posts: 1816
Location: Austin, TX
Well, then that would next lead me to think that the entity your are trying to "update" is a detached instance and you never explicitly reattch it to a session.

I need to see the code that calls into the code you previously posted.


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 11, 2005 12:02 pm 
Regular
Regular

Joined: Wed Sep 29, 2004 11:34 am
Posts: 62
Location: Houston, TX
Here is a simple object that gets updated as needed:

Code:
    @MethodPermissions({"Sales"})
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    private void updateBooking(Booking booking) {
        BookingDAO dao = new BookingDAO();
        booking.setLastAccessed(new Date());
        try {
            dao.update(booking);
            createAudit(booking.getId(), dif);
        }
        catch (Exception e) {log.error(e.getMessage());}
    } 

    @MethodPermissions({"Sales"})
     @TransactionAttribute(TransactionAttributeType.REQUIRED)
     private void createAudit(long bid, String comments) {
         BookingAuditDAO dao = new BookingAuditDAO();
         BookingAudit audit = new BookingAudit();
         audit.setEmployeeID(emp.getEmployee());
         audit.setCreateTime(new Date());
         audit.setBookingID(new Booking(bid));
         audit.setComments(comments);
         try {
             dao.save(audit);
         }
         catch (Exception e) {log.error(e.getMessage());}
     }


You see after the update we create an audit. The audit saves fine, but the update nevers goes through.


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 11, 2005 1:10 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 3:00 pm
Posts: 1816
Location: Austin, TX
What is going on here:
audit.setBookingID(new Booking(bid));


In general, it is best to parse code sections that you are having problems with down to minimal pieces and see where things start to break down. For example, in straight-line logic, your processing here is really as simple as:
Code:
void updateBooking(Booking booking) {
    booking.setLastAccessed(new Date());

    Session s = null;
    Transaction txn = null;

    /////////////////////////////////////////////////////////////
    // analogous to your dao.update() call...
    /////////////////////////////////////////////////////////////
    try {
        s = getSession();
        txn = s.beginTransaction();
        s.update( booking );
        txn.commit();
    }
    catch (HibernateException e) {
        rollback( txn );
    }
    finally {
        release( session );
    }

    s = null;
    txn = null;

    /////////////////////////////////////////////////////////////
    // analogous to your createAudit() call...
    /////////////////////////////////////////////////////////////
    BookingAudit audit = new BookingAudit();
    audit.setEmployeeID( emp.getEmployee() );
    audit.setCreateTime( new Date() );
    audit.setBookingID( new Booking( booking.getId() ) );
    audit.setComments( dif );
    try {
        s = getSession();
        txn = s.beginTransaction();
        s.save( audit );
        txn.commit();
    }
    catch (HibernateException e) {
        rollback( txn );
    }
    finally {
        release( session );
    }

}

private void rollback(Transaction transaction) {
    if ( transaction != null ) {
        try {
            transaction.rollback();
        }
        catch( Throwable ignore ) {
            // don't really care; the cause for rolling back is more important
        }
    }
}

private void release(Session session) {
    if ( session != null ) {
        try {
            session.close();
        }
        catch( Throwable ignore ) {
        }
    }
}



Another thing that comes into play here is the actual transaction semantics. Is a single JTA trsnaction in effect foor the entire updateBooking() processing?


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 11, 2005 1:22 pm 
Regular
Regular

Joined: Wed Sep 29, 2004 11:34 am
Posts: 62
Location: Houston, TX
Steve I checked to see if the transaction is committed and it does commit. It works the same way when I want to save, and it works fine, but it seems that there is something that is holding it back from actually updating or deleting. The following is my hibernate-service.xml:

Code:
<server>
- <mbean code="org.jboss.hibernate.jmx.Hibernate" name="jboss.har:service=Hibernate">
  <attribute name="DatasourceName">java:/MySqlDS</attribute>
  <attribute name="Dialect">org.hibernate.dialect.MySQLDialect</attribute>
  <attribute name="SessionFactoryName">java:/hibernate/HibernateFactory</attribute>
  <attribute name="CacheProviderClass">org.hibernate.cache.TreeCacheProvider</attribute>
  <attribute name="ShowSqlEnabled">false</attribute>
  </mbean>
  </server>


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 11, 2005 1:34 pm 
Regular
Regular

Joined: Wed Sep 29, 2004 11:34 am
Posts: 62
Location: Houston, TX
Inside of updateBooking() the createAudit() works fine and it creates the audit, but the update does not work. I can even take the createAudit() for testing purposes and the same result.

Quote:
Another thing that comes into play here is the actual transaction semantics. Is a single JTA trsnaction in effect foor the entire updateBooking() processing?


Yes in the end, we would like it to be one transaction. Let me give you our Project skeleton:

DAO, POJOs, mappings, _rootDAO (the file that I posted with the threadedSessions, update, delete, etc) - Inside a HAR file and deployed seperately
EJBs - deployed seperately

We did not want to sprinkle any Hibernate internal code that deals with session, etc so we put it all in our DAOs.

Everything seemed to work fine in Hibernate 2 (save, update, etc.) When we had any problems with any objects, we were even successful in our rollback which was controlled by our EJB.


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.