-->
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.  [ 6 posts ] 
Author Message
 Post subject: ClassCastException problem in hibernate
PostPosted: Sun Jun 17, 2007 8:10 pm 
Newbie

Joined: Wed Apr 11, 2007 2:11 pm
Posts: 10
I am getting a ClassCastException from within the Hibernate API while trying to save a new POJO, which has a one-to-many relationship with another POJO. Here is my stack trace
Code:
      Exception in thread "main" java.lang.ClassCastException: java.lang.Boolean canno
t be cast to java.lang.String
        at org.hibernate.type.StringType.toString(StringType.java:44)
        at org.hibernate.type.NullableType.nullSafeToString(NullableType.java:93
)
        at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:140)
        at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:107)
        at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(Abst
ractEntityPersister.java:1997)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(Abstrac
tEntityPersister.java:2243)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(Abstrac
tEntityPersister.java:2640)
        at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentit
yInsertAction.java:48)
        at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
        at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplic
ate(AbstractSaveEventListener.java:298)
        at org.hibernate.event.def.AbstractSaveEventListener.performSave(Abstrac
tSaveEventListener.java:181)
        at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId
(AbstractSaveEventListener.java:107)
        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGene
ratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
        at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrR
equestedId(DefaultSaveEventListener.java:33)
        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTran
sient(DefaultSaveOrUpdateEventListener.java:172)
        at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(
DefaultSaveEventListener.java:27)
        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpda
te(DefaultSaveOrUpdateEventListener.java:70)
        at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
        at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
        at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
        at server.dao.help.FormDAOVisitor.create(FormDAOVisitor.j
ava:53)
        at server.dao.PIFormDAO.doCreate(PIFormDAO.java:88)
        at server.dao.DAO.create(DAO.java:45)
        at server.BaseAccessLayer.create(BaseAccessLayer.java:28)

        at server.SessionDataAccessLayer$1.process(SessionDataAcc
essLayer.java:35)
        at server.SessionAdaptor.run(SessionAdaptor.java:57)
        at java.lang.Thread.run(Unknown Source):44)
        at org.hibernate.type.NullableType.nullSafeToString(NullableType.java:93


As you can see the ClassCastExceptipon originates deep within hibernate API this looks like some kind of bug therefore after investigating the problem and I found this http://opensource.atlassian.com/project ... e/HHH-2052 bug in the bug database. But I am not really sure if this is a manifestation of this bug so would really appreciate any body looking into this. Also if this bug were the cause would any of you know an effective workaround?

Also if you need any more information such as POJO code or hibernate mapping file just let me know. Thanks and please help me I am a bit stuck on this issue.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 18, 2007 12:33 am 
Expert
Expert

Joined: Tue Jan 30, 2007 12:45 am
Posts: 283
Location: India
Hi sb5100,

Post your POJO ,HBM and table Desc .And environment detail (jars) .

_________________
Dharmendra Pandey


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 18, 2007 6:03 am 
Newbie

Joined: Wed Apr 11, 2007 2:11 pm
Posts: 10
dharmendra.pandey wrote:
Hi sb5100,

Post your POJO ,HBM and table Desc .And environment detail (jars)
.

The following POJO can be saved without any Exceptions which is User
Code:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="protocol.hbm.User" table="user">
        <id name="id" type="string">
            <generator class="server.DateIdGenerator"/>
        </id>
        <property name="uname" column="uname"/>
    </class>

</hibernate-mapping>

Here is the POJO
Code:
package protocol.hbm;
import java.io.Serializable;



public class User  implements Serializable {
   public static final long serialVersionUID = 6632533009l;
   private String id;
   private String uname;
   
   /**
    * Default constructor required by hibernate
    */
   public User(){
      
   }
   
   public User(String uname){
      setUname(uname);

   }
   
   public String getId(){
      return id;
   }
   
   void setId(String id){
      this.id = id;
   }
   
   public String getUname(){
      return uname;
   }
   
   public void setUname(String uname){
      this.uname = uname;
   }
   
   public int getColor(){
      return 0;
   }
   
   public boolean equals(Object obj){
      if(!(obj instanceof User)){
         return false;
      }
      User rhs = (User)obj;
      return getUname().equals(rhs.getUname());
   }
   

}



But when saving PIForm, which has a one-to-many relationship whit an instanceof, a saved user I get this exception. The POJO class and mapping is as follows
Mapping File
Code:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <joined-subclass name=" protocol.hbm.PIForm"
                          extends="protocol.hbm.access.RestrictedAccess"
                          table="pi_form">
       <key column="ra_id"/>
        <many-to-one
            name="user"
            class="protocol.hbm.User"
            column="userId"
            not-null="true"
            unique="true"/>
        <set name="telephones"  cascade="all,delete-orphan">
            <key column="pi_form_id"/>
            <one-to-many class=" protocol.hbm.Telephone"/>
        </set>
        <property name="firstname" type="string" length="32"/>
        <property name="lastname" type="string" length="32"/>
        <property name="forenames" type="string" length="128"/>
        <property name="title" type="string" length="16"/>
        <property name="email" type="string" length="32"/>
        <property name="ismale" type="string" length="32"/>
        <property name="dob" type="timestamp"/>
        <set name="addresses" cascade="all,delete-orphan">
            <key column="pi_form_id"/>
            <one-to-many class=" protocol.hbm.Address"/>
        </set>

    </joined-subclass>

</hibernate-mapping>

POJO code

Code:
package protocol.hbm;
import java.util.Set;
import java.util.HashSet;
import java.sql.Date;
import protocol.IllegalFieldValueException;
/**
* This stands for Personal Information form. this class defines aabstract information
* about a person involved with the organaization such as a student or staff member
*
* @author Wiraj Rohitha Bibile
*
*/
//mapping document created
public class PIForm extends uk.org.wrtrust.protocol.hbm.access.RestrictedAccess{
   public static final long serialVersionUID=100987;
   private Set<Telephone> telephones = new HashSet<Telephone>();
   private Set<Address> addresses = new HashSet<Address>();
   private String firstname;//
   private String lastname;//
   private String forenames;//
   private String title;//
   private String email;
   private boolean ismale;
   private Date dob;//
   private User user;

   /*
    * Nationality of the person
    */
   private String nationality = "British";
   
   public PIForm(){
      
   }
   
   public Set<Telephone> getTelephones(){
      return telephones;
   }
   
   public void setTelephones(Set<Telephone> telephones){
      this.telephones = telephones;
   }
   
   public Set<Address> getAddresses(){
      return addresses;
   }
   
   public void setAddresses(Set<Address> addresses){
      this.addresses = addresses;
   }
   
   public String getFirstname(){
      return firstname;
   }
   
   public void setFirstname(String firstname){
      this.firstname = firstname;
   }
   
   public String getLastname(){
      return lastname;
   }
   
   public void setLastname(String lastname){
      this.lastname = lastname;
   }
   
   public String getTitle(){
      return title;
   }
   
   public void setTitle(String title){
      this.title = title;
   }
   
   public String getForenames(){
      return forenames;
   }
   
   public void setForenames(String forenames){
      this.forenames = forenames;
   }
   
   public String getEmail(){
      return email;
   }
   
   public void setEmail(String email){
      this.email = email;
   }
   public User getUser(){
      return user;
   }
   
   public void setUser(User user){
      this.user = user;
   }
   
   public Date getDob(){
      return dob;
   }
   
   public void setDob(Date dob){
      this.dob= dob;
   }
   
   public String getNationality(){
      return nationality;
   }
   
   public void setNationality(String nationality){
      this.nationality = nationality;
   }
   
   //public PIForm(String name)
   
   public static class Titles{
      private static final String titles[]={"Mr","Mrs","Miss","Ms","Rev","Dr","Prof","Other"};
      public static String[] getTitles(){
         String titles[] = new String[PIForm.Titles.titles.length];
         System.arraycopy(PIForm.Titles.titles,0,titles,0,PIForm.Titles.titles.length);
         return titles;
      }
      
      public static String validate(String title){
         title= title.trim();
         for(String titleName:titles){
            if(titleName.equalsIgnoreCase(title)){
               return titleName;
            }
         }
         throw new IllegalFieldValueException(title+" is not a recogernised title!");
      }
      
      
   }


   /**
    * @return the ismale
    */
   public boolean getIsmale() {
      return ismale;
   }

   /**
    * @param ismale the ismale to set
    */
   public void setIsmale(boolean ismale) {
      this.ismale = ismale;
   }

   /* (non-Javadoc)
    * @see java.lang.Object#hashCode()
    */
   @Override
   public int hashCode() {
      final int PRIME = 31;
      int result = 1;
      result = PRIME * result + ((dob == null) ? 0 : dob.hashCode());
      result = PRIME * result + ((email == null) ? 0 : email.hashCode());
      result = PRIME * result + ((firstname == null) ? 0 : firstname.hashCode());
      result = PRIME * result + ((forenames == null) ? 0 : forenames.hashCode());
      result = PRIME * result + (ismale ? 1231 : 1237);
      result = PRIME * result + ((lastname == null) ? 0 : lastname.hashCode());
      result = PRIME * result + ((nationality == null) ? 0 : nationality.hashCode());
      result = PRIME * result + ((title == null) ? 0 : title.hashCode());
      result = PRIME * result + ((user == null) ? 0 : user.hashCode());
      return result;
   }

   /* (non-Javadoc)
    * @see java.lang.Object#equals(java.lang.Object)
    */
   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      final PIForm other = (PIForm) obj;
      if (dob == null) {
         if (other.dob != null)
            return false;
      } else if (!dob.equals(other.dob))
         return false;
      if (email == null) {
         if (other.email != null)
            return false;
      } else if (!email.equals(other.email))
         return false;
      if (firstname == null) {
         if (other.firstname != null)
            return false;
      } else if (!firstname.equals(other.firstname))
         return false;
      if (forenames == null) {
         if (other.forenames != null)
            return false;
      } else if (!forenames.equals(other.forenames))
         return false;
      if (ismale != other.ismale)
         return false;
      if (lastname == null) {
         if (other.lastname != null)
            return false;
      } else if (!lastname.equals(other.lastname))
         return false;
      if (nationality == null) {
         if (other.nationality != null)
            return false;
      } else if (!nationality.equals(other.nationality))
         return false;
      if (title == null) {
         if (other.title != null)
            return false;
      } else if (!title.equals(other.title))
         return false;
      if (user == null) {
         if (other.user != null)
            return false;
      } else if (!user.equals(other.user))
         return false;
      return true;
   }
}


Here is the database schema
Code:
mysql> describe user;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | varchar(255) | NO   | PRI |         |       |
| uname | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.02 sec)

mysql> describe pi_form;
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| ra_id     | int(11)      | NO   | PRI |         |       |
| userId    | varchar(255) | NO   | UNI |         |       |
| firstname | varchar(32)  | YES  |     | NULL    |       |
| lastname  | varchar(32)  | YES  |     | NULL    |       |
| forenames | varchar(128) | YES  |     | NULL    |       |
| title     | varchar(16)  | YES  |     | NULL    |       |
| email     | varchar(32)  | YES  |     | NULL    |       |
| ismale    | varchar(32)  | YES  |     | NULL    |       |
| dob       | datetime     | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 18, 2007 7:04 am 
Newbie

Joined: Wed Apr 11, 2007 2:11 pm
Posts: 10
I wrote a small test program to demonstrate this problem and the problem persist as expected .

Code:
package test;
import protocol.hbm.*;
import server.dao.*;
import org.hibernate.*;
import java.io.*;



/**
* PIForm creation Test
*
*/
public class PIFormCreateTest {

   /**
    * @param args
    */
   public static void main(String[] args)throws Exception{
      rawTest();

   }


   public static void rawTest()throws Exception{
      System.out.println("Running Raw Test");
      StaffUser stau = new StaffUser("test user name","test description");
      Session session = HibernateHelper.getSession();
      Transaction tx = null;
      try {
         tx = session.beginTransaction();
         System.out.println("Saving test user");
         session.save(stau);
         System.out.println("User saved");
         tx.commit();
      }
      catch (Exception e) {
         System.out.println("Exception Couldnot save User \nrolling back transaction");
         tx.rollback();
         System.out.println("Roll back done");
         System.out.println("Printing Exception stack trace");
         e.printStackTrace();
         return;
      }
      PIForm piform = new PIForm();
      piform.getTelephones().add(new Telephone("00993376",Telephone.HOME));
      piform.getAddresses().add(new Address("999","South Road","North City","East County","UP7 7DR"));
      piform.setEmail("alpha@beta.theta.gamma");
      piform.setFirstname("Tester");
      piform.setLastname("raw Tester");
      piform.setForenames("x");
      piform.setUser(stau);
      piform.setIsmale(true);
      try {
         tx = session.beginTransaction();
         session.save(piform);
         tx.commit();
      }
      catch (Exception e) {
         System.out.println("Exception Couldnot save PIForm \nrolling back transaction");
         tx.rollback();
         System.out.println("Roll back done");
         System.out.println("Deleting test user");
         session.delete(stau);
         System.out.println("Test User deletion done");
         System.out.println("Printing Exception stack trace");
         e.printStackTrace();
         return;
      }
      pause("Waiting for clean up");
      System.out.println("Cleaning up");
      
      tx = session.beginTransaction();
      session.delete(piform);
      session.delete(stau);
      tx.commit();
      

   }
   
   public static void pause(String message)throws Exception{
      if(message!=null){
         System.out.println(message);
      }
      System.out.print("Press Enter to Continue...");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      br.readLine();
   }
}


And the output is
Code:
Running Raw Test
Saving test user
User saved
Exception Couldnot save PIForm
rolling back transaction
Roll back done
Deleting test user
Test User deletion done
Printing Exception stack trace
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Stri
ng
        at org.hibernate.type.StringType.toString(StringType.java:44)
        at org.hibernate.type.NullableType.nullSafeToString(NullableType.java:93
)
        at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:140)
        at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:107)
        at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(Abst
ractEntityPersister.java:1997)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(Abstrac
tEntityPersister.java:2243)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(Abstrac
tEntityPersister.java:2640)
        at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentit
yInsertAction.java:48)
        at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
        at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplic
ate(AbstractSaveEventListener.java:298)
        at org.hibernate.event.def.AbstractSaveEventListener.performSave(Abstrac
tSaveEventListener.java:181)
        at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId
(AbstractSaveEventListener.java:107)
        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGene
ratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
        at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrR
equestedId(DefaultSaveEventListener.java:33)
        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTran
sient(DefaultSaveOrUpdateEventListener.java:172)
        at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(
DefaultSaveEventListener.java:27)
        at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpda
te(DefaultSaveOrUpdateEventListener.java:70)
        at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
        at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
        at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
        at test.PIFormCreateTest.rawTest(PIFormCreateTest.java:56
)
        at PIFormCreateTest.main(PIFormCreateTest.java:20)


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 18, 2007 7:12 am 
Senior
Senior

Joined: Thu May 17, 2007 2:31 am
Posts: 194
Location: Sri Lanka
Hi

in your Table structure ismale is varchar(32) but in your code it is boolean


Amila

(Don't forget to rate if helps)


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 18, 2007 12:15 pm 
Newbie

Joined: Wed Apr 11, 2007 2:11 pm
Posts: 10
amila733 wrote:
Hi

in your Table structure ismale is varchar(32) but in your code it is boolean


Amila

(Don't forget to rate if helps)

Thanks for your help really appreciate it


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