-->
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: unexpected ClassCastException with uniqueResult() method
PostPosted: Sun Nov 11, 2007 3:50 pm 
Newbie

Joined: Sun Nov 11, 2007 3:41 pm
Posts: 3
The problem
I want a very simple login procedure, and i use database records for storing usernames and passwords.

I have a HQL named query defined, and it all gets executed well. I also have one result back for my test user account (username='test' and password='test').

When i do query.uniqueResult(); , it returns an Object[] which represents a row. I would expect it was mapped my persistent class User which is mapped and so forth.

So, what am i doing wrong here? The classcastexception itself is explainable, since i can't cast an Object[] to a User class. But why is hibernate not doing this?

Thanks in advance for any help given!

Hibernate version:
version 3.2.5

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

<hibernate-mapping>
    <class name="nl.database.hibernate.persistence.User" table="USERS">

        <id name="id" column="ID">
            <generator class="native"/>
        </id>

        <property name="username" type="string" column="USERNAME"/>
        <property name="password" type="string" column="PASSWORD"/>
    </class>
   
   <sql-query name="getUserByUsernamePassword">
      select * from users where username = ? and password = ?
   </sql-query>
</hibernate-mapping>


and the code:
Code:
package nl.database.hibernate.persistence;

public class User implements java.io.Serializable {

   private Integer id;

    private String username;
    private String password;
   
    public User() {}

    public Integer getId() {
        return id;
    }

    private void setId(Integer id) {
        this.id = id;
    }

    public void setUsername(String username) {
       this.username = username;
    }
   
    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
   
    public void setPassword(String password) {
       this.password = password;
    }
   
    public String toString() {
       return "Id=" + id + " | Username= " + username + " | Password = " + password;
    }

}


Code between sessionFactory.openSession() and session.close():
Code:
boolean mayLogin = false;
         Session session = HibernateFactory.getSessionFactory().openSession();
         try {
            
            // nl.database.hibernate.persistence.Users.
             Query query = session.getNamedQuery("getUserByUsernamePassword");
             query.setString(0, username);
             query.setString(1, password);
      
             logger.debug("Fetching a user from the database");
             User aUser = (User)query.uniqueResult();
            
             if (aUser != null) {
                logger.debug(aUser.toString());
                mayLogin = true;
             } else {
                logger.debug("No user found with username = " + username + " and password " + password);
             }
            
         } catch(Exception e ) {
            logger.debug(e);
         } finally {
            logger.debug("HIBERNATE: Closing session");
            session.close();            
         }


Full stack trace of any exception that occurs:
20:30:58,666 DEBUG [AbstractBatcher] preparing statement
20:30:58,688 DEBUG [StringType] binding 'test' to parameter: 1
20:30:58,691 DEBUG [StringType] binding 'test' to parameter: 2
20:30:58,695 DEBUG [AbstractBatcher] about to open ResultSet (open ResultSets: 0, globally: 0)
20:30:58,720 DEBUG [Loader] processing result set
20:30:58,723 DEBUG [Loader] result set row: 0
20:30:58,726 DEBUG [Loader] result row:
20:30:58,729 DEBUG [IntegerType] returning '1' as column: ID
20:30:58,732 DEBUG [StringType] returning 'test' as column: USERNAME
20:30:58,735 DEBUG [StringType] returning 'test' as column: PASSWORD
20:30:58,738 DEBUG [Loader] done processing result set (1 rows)
20:30:58,741 DEBUG [AbstractBatcher] about to close ResultSet (open ResultSets: 1, globally: 1)
20:30:58,744 DEBUG [AbstractBatcher] about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
20:30:58,747 DEBUG [AbstractBatcher] closing statement
20:30:58,755 DEBUG [StatefulPersistenceContext] initializing non-lazy collections
20:30:58,761 DEBUG [JDBCContext] after autocommit
20:30:58,764 DEBUG [ConnectionManager] aggressively releasing JDBC connection
20:30:58,768 DEBUG [ConnectionManager] releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
20:30:58,774 DEBUG [DriverManagerConnectionProvider] returning connection to pool, pool size: 1
20:30:58,776 DEBUG [DoLoginHandler] java.lang.ClassCastException: [Ljava.lang.Object;
20:30:58,779 DEBUG [DoLoginHandler] HIBERNATE: Closing session
20:30:58,782 DEBUG [SessionImpl] closing session
20:30:58,785 DEBUG [ConnectionManager] connection already null in cleanup : no action


Name and version of the database you are using:
mySQL

The generated SQL (show_sql=true):
See above


Top
 Profile  
 
 Post subject: additional information
PostPosted: Sun Nov 11, 2007 4:03 pm 
Newbie

Joined: Sun Nov 11, 2007 3:41 pm
Posts: 3
Additional information:
When doing it the other way around. I can succesfully save a User by doing:

Code:
User aNewUser = new User();
aNewUser.setPassword(password);
aNewUser.setUsername(username);
session.beginTransaction();
session.save(aNewUser);
session.getTransaction().commit();


Top
 Profile  
 
 Post subject:
PostPosted: Sun Nov 11, 2007 7:15 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 6:10 am
Posts: 8615
Location: Neuchatel, Switzerland (Danish)
your query is an native SQL query returning the value of the columns you are asking about. use a hql query or map the native sql query correctly; see the docs.

_________________
Max
Don't forget to rate


Top
 Profile  
 
 Post subject:
PostPosted: Mon Nov 12, 2007 4:49 am 
Newbie

Joined: Sun Nov 11, 2007 3:41 pm
Posts: 3
Unbelievable i did not see that in the first place. Probably too much staring at
the code for too long and too late :)

It works as a charm now! Thanks!


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.