-->
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.  [ 5 posts ] 
Author Message
 Post subject: Can't load simple object
PostPosted: Wed Aug 04, 2004 6:10 pm 
Newbie

Joined: Mon Aug 02, 2004 5:33 am
Posts: 4
Hi

I am having multiple problems using Hibernate with a small number of simple objects. I can't load my User object and I don't know why. Have I got my mapping wrong?

I get the following exception:

net.sf.hibernate.WrongClassException: Object with id: 21275acd23bf65dab1b1acdb47
23dc2b was not of the specified subclass: com.cms.shared.data.User (loaded object was of wrong class)
at net.sf.hibernate.loader.Loader.instanceAlreadyLoaded(Loader.java:456)
at net.sf.hibernate.loader.Loader.getRow(Loader.java:423)
at net.sf.hibernate.loader.Loader.doQuery(Loader.java:209)
at net.sf.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections
(Loader.java:133)
at net.sf.hibernate.loader.Loader.doList(Loader.java:955)
at net.sf.hibernate.loader.Loader.list(Loader.java:946)
at net.sf.hibernate.hql.QueryTranslator.list(QueryTranslator.java:834)
at net.sf.hibernate.impl.SessionImpl.find(SessionImpl.java:1536)
at net.sf.hibernate.impl.SessionImpl.find(SessionImpl.java:1513)
at net.sf.hibernate.impl.SessionImpl.find(SessionImpl.java:1505)

This is what's in Hibernate log:

23:02:46,569 INFO Environment:462 - Hibernate 2.1.3
23:02:46,589 INFO Environment:491 - hibernate.properties not found
23:02:46,589 INFO Environment:519 - using CGLIB reflection optimizer
23:02:46,609 INFO Configuration:872 - configuring from resource: /hibernate.cfg.xml
23:02:46,609 INFO Configuration:844 - Configuration resource: /hibernate.cfg.xml
23:02:46,989 INFO Configuration:328 - Mapping resource: User.hbm.xml
23:02:47,180 INFO Binder:229 - Mapping class: com.cms.shared.data.User -> cms_user
23:02:47,420 INFO Configuration:328 - Mapping resource: UserType.hbm.xml
23:02:47,440 INFO Binder:229 - Mapping class: com.cms.shared.data.UserType -> cms_usertype
23:02:47,440 INFO Configuration:328 - Mapping resource: Document.hbm.xml
23:02:47,470 INFO Binder:229 - Mapping class: com.cms.shared.data.Document -> cms_document
23:02:47,470 INFO Configuration:328 - Mapping resource: Company.hbm.xml
23:02:47,500 INFO Binder:229 - Mapping class: com.cms.shared.data.Company -> cms_company
23:02:47,500 INFO Configuration:328 - Mapping resource: UserLogin.hbm.xml
23:02:47,520 INFO Binder:229 - Mapping class: com.cms.shared.data.UserLogin -> cms_user
23:02:47,520 INFO Configuration:1030 - Configured SessionFactory: null
23:02:47,530 INFO Configuration:613 - processing one-to-many association mappings
23:02:47,530 INFO Configuration:622 - processing one-to-one association property references
23:02:47,530 INFO Configuration:647 - processing foreign key constraints
23:02:47,590 INFO Dialect:82 - Using dialect: net.sf.hibernate.dialect.MySQLDialect
23:02:47,590 INFO SettingsFactory:62 - Use outer join fetching: false
23:02:47,610 INFO NamingHelper:26 - JNDI InitialContext properties:{}
23:02:47,650 INFO DatasourceConnectionProvider:51 - Using datasource: java:comp/env/jdbc/cms
23:02:47,670 INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of process level read-write cache is not recommended)
23:02:47,991 INFO SettingsFactory:102 - Use scrollable result sets: true
23:02:47,991 INFO SettingsFactory:105 - Use JDBC3 getGeneratedKeys(): true
23:02:47,991 INFO SettingsFactory:108 - Optimize cache for minimal puts: false
23:02:48,001 INFO SettingsFactory:114 - echoing all SQL to stdout
23:02:48,001 INFO SettingsFactory:117 - Query language substitutions: {}
23:02:48,001 INFO SettingsFactory:128 - cache provider: net.sf.ehcache.hibernate.Provider
23:02:48,011 INFO Configuration:1093 - instantiating and configuring caches
23:02:48,281 INFO SessionFactoryImpl:119 - building session factory
23:02:48,662 INFO ReflectHelper:176 - reflection optimizer disabled for: com.cms.shared.data.UserLogin, IllegalArgumentException: Cannot find matching method/constructor
23:02:48,742 INFO ReflectHelper:176 - reflection optimizer disabled for: com.cms.shared.data.Company, IllegalArgumentException: Cannot find matching method/constructor
23:02:48,762 INFO ReflectHelper:176 - reflection optimizer disabled for: com.cms.shared.data.User, IllegalArgumentException: Cannot find matching method/constructor
23:02:48,772 INFO ReflectHelper:176 - reflection optimizer disabled for: com.cms.shared.data.Document, IllegalArgumentException: Cannot find matching method/constructor
23:02:48,792 INFO ReflectHelper:176 - reflection optimizer disabled for: com.cms.shared.data.UserType, IllegalArgumentException: Cannot find matching method/constructor
23:02:49,052 INFO SessionFactoryObjectFactory:82 - no JNDI name configured
23:02:49,242 DEBUG SQL:237 - select userlogin0_.user_id as user_id, userlogin0_.username as username, userlogin0_.password as password from cms_user userlogin0_ where (userlogin0_.username='FERRS' )and(userlogin0_.password='BLUEBERRY' )
23:02:49,293 DEBUG StringType:68 - returning '21275acd23bf65dab1b1acdb4723dc2b' as column: user_id
23:02:49,293 DEBUG StringType:68 - returning 'FERRS' as column: username
23:02:49,293 DEBUG StringType:68 - returning 'BLUEBERRY' as column: password
23:02:49,303 DEBUG SQL:237 - select user0_.user_id as user_id, user0_.firstname as firstname, user0_.surname as surname, user0_.email as email, user0_.company_id as company_id, user0_.usertype_id as usertype6_ from cms_user user0_ where (user0_.user_id='21275acd23bf65dab1b1acdb4723dc2b' )
23:02:49,313 DEBUG StringType:68 - returning '21275acd23bf65dab1b1acdb4723dc2b' as column: user_id

This is my User table
Code:
CREATE TABLE cms_user
(
user_id VARCHAR(32) NOT NULL  PRIMARY KEY,
username VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL,
firstname VARCHAR(32) NOT NULL,
surname VARCHAR(32) NOT NULL,
email VARCHAR(64) NOT NULL,
usertype_id VARCHAR(32) NOT NULL REFERENCES cms_usertype(usertype_id),
company_id VARCHAR(32) NOT NULL REFERENCES cms_company(company_id)
)TYPE=InnoDB;


Mapping:
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>

    <class name="com.cms.shared.data.User" table="cms_user">

        <!-- A 32 hex character is the surrogate key. It's automatically
            generated by Hibernate with the UUID pattern. -->
        <id name="id" type="string" unsaved-value="null" >
            <column name="user_id" sql-type="char(32)" not-null="true"/>
            <generator class="uuid.hex"/>
        </id>

        <property name="firstName" column="firstname" type="string" not-null="true" />

        <property name="surname" column="surname" type="string" not-null="true" />

        <property name="email" column="email" type="string" not-null="true" />
       
       <many-to-one name="company" column="company_id" class="com.cms.shared.data.Company"
        cascade="none" />

      <many-to-one name="type" column="usertype_id" class="com.cms.shared.data.UserType"
       cascade="none" />

    </class>

</hibernate-mapping>



I have been trying to get this working for the past few days without any success. Any information or help from anyone would be greatly appreciated.

Thanks in advance.
[/code]


Top
 Profile  
 
 Post subject:
PostPosted: Wed Aug 04, 2004 7:48 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 7:19 pm
Posts: 2364
Location: Brisbane, Australia
show the snippet code you use to load the object.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 05, 2004 5:15 am 
Newbie

Joined: Mon Aug 02, 2004 5:33 am
Posts: 4
Here's the methods in my DAO classs that load the object.

Code:
public User getUserByUsernamePassword(String name, String password)
     throws ExceptionInInitializerError, HibernateException
   {
      User user = null;
      Transaction transaction = null;
      
      // check that the arguments name and password is valid
      Assert.notNullNotEmpty("The String argument name has length < 1.", name);
      Assert.notNullNotEmpty("The String argument password has length < 1.",
        password);
      
      try
      {
         
         m_session = HibernateUtil.currentSession();
         
         transaction = m_session.beginTransaction();
         
          List result = m_session.find("FROM UserLogin as ul WHERE ul.username = '" +
              name.toUpperCase() + "' and ul.password = '" +
              password.toUpperCase() + "'");
         // if the username and password is not correct return User as null
         
         if(!result.isEmpty() || result.size() == 1)
         {
            UserLogin userLogin = (UserLogin)result.get(0);
            String userId = userLogin.getUserId();
         
            // now to get User object by Id.
            user = getUserById(userId);
         }

         transaction.commit();
         
      }
      catch(ExceptionInInitializerError e)
      {
         e.printStackTrace();
         throw e;
      }
      catch(HibernateException e)
      {
         e.printStackTrace();
         throw e;
      }
      finally
      {
         if(transaction != null)
            //transaction.rollback();
         try
         {
            HibernateUtil.closeSession();
            
         }
         catch(ExceptionInInitializerError e)
         {
            e.printStackTrace();
            throw e;
         }
         catch(HibernateException e)
         {
            e.printStackTrace();
            throw e;
         }
         
      }
      return user;
   }
   
   /**
    * Returns the User object that has the specified userId.
    *
    * @param userId  the specified userId
    *
    * @return User  the user
    *
    * @throws HibernateException  if there is an error in persistent layer or
    *                             JDBC driver.
    */
   public User getUserById(String userId) throws ExceptionInInitializerError,
      HibernateException
   {
      User user = null;
      Transaction transaction = null;
      
      try
      {
         m_session = HibernateUtil.currentSession();
         transaction = m_session.beginTransaction();
         
         System.out.println("The argument userId is " + userId);
         
         List result = m_session.find("FROM User as u WHERE u.id = '" + userId + "'");
         
         if(!result.isEmpty() || result.size() == 1)
         {
            System.out.println("we found the user search by id.");
            user = (User)result.get(0);
         }
         System.out.println("Empty result for userbyid.");
         transaction.commit();
         System.out.println("Tramsaction committed in userbyId");
         
      }
      catch(ExceptionInInitializerError e)
      {
         e.printStackTrace();
         throw e;
      }
      catch(HibernateException e)
      {
         e.printStackTrace();
         throw e;
      }
      finally
      {
         if(transaction != null)
            //transaction.rollback();
         try
         {
            HibernateUtil.closeSession();
         }
         catch(ExceptionInInitializerError e)
         {
            System.out.println("Finally block getUserById: " + e.getMessage());
            e.printStackTrace();
            throw e;
         }
         catch(HibernateException e)
         {
            e.printStackTrace();
            throw e;
         }
         
      }
      return user;
   }


Code:
public class HibernateUtil
{
   private static final SessionFactory sessionFactory;
   public static final ThreadLocal session = new ThreadLocal();

   static {
        try {
          Configuration configuration = new Configuration();
          sessionFactory = configuration.configure().buildSessionFactory();
        } catch (Throwable ex) {
          throw new ExceptionInInitializerError(ex);
        }
      }

   
   public static Session currentSession() throws HibernateException
   {
      Session s = (Session) session.get();
      // Open a new Session, if this Thread has none yet
      if (s == null)
      {
         s = sessionFactory.openSession();
         session.set(s);
   
      }
      return s;
   }

   public static void closeSession() throws HibernateException
   {
      try
      {
         Session s = (Session) session.get();
         session.set(null);
         if (s != null)
            s.close();
      }
      catch(Throwable t){
         t.printStackTrace();
      }
   }

}


I seem to have another problem with calling rollback() even though my tables are of InnoDB type. It can't roll back because autocommit is set to true. I thought Hibernate turns off the autocommit .I'm using MySQL4.0.20.

Many thanks


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 05, 2004 10:54 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 7:19 pm
Posts: 2364
Location: Brisbane, Australia
Only two comments:
1) Use prepared statements don't concate strings.
2) Only map one class to a table. You have UserLogin and User both mapped to cms_user. Remove one of the mappings and try again.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 06, 2004 7:48 am 
Newbie

Joined: Mon Aug 02, 2004 5:33 am
Posts: 4
Thanks David

It works now after changing the mapping as you suggested.


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