-->
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.  [ 7 posts ] 
Author Message
 Post subject: Hibernate inheritence issue
PostPosted: Wed Apr 03, 2013 9:23 am 
Newbie

Joined: Tue Mar 19, 2013 5:46 am
Posts: 3
Hi All,
I am using Hibernate 4.2.0 with spring framework integration.

I am using the hibernate inheritance for mapping Person to Patient and User.

My bean definition is as follows

Code:
@Entity
@Table ( name = "person" )
@Inheritance(strategy=InheritanceType.JOINED)
public class Person implements Serializable
{
   @Id
   @Column ( name = "PERSON_ID" )
   @GeneratedValue( strategy=GenerationType.AUTO)
   private int                     personId;
   
   @OneToMany ( mappedBy="person", fetch=FetchType.EAGER)
   private Set<Address> addresses;

   @Column ( name = "FIRST_NAME" )
   private String                  firstName;

   @Column ( name = "LAST_NAME" )
   private String                  lastName;
}


My Patient bean is defined as follows

Code:
@Entity
@Table(name="patient")
@PrimaryKeyJoinColumn(name="person_id")
public class Patient extends Person implements Serializable
{
   @Column(name="patient_id")
   @GeneratedValue(strategy=GenerationType.AUTO)
   private int patientId;
}


My User bean is as follows
Code:
@Entity
@Table(name = "user")
@PrimaryKeyJoinColumn(name = "person_id")
public class User extends Person implements Serializable
{
   @Column(name = "USER_ID")
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private int userId;
   
   @Column(name = "INSTITUTION_NAME")
   private String institutionName;
}


As Address is common for both Patient and User, I put the mapping in the Person bean.

My Address bean definition is as follows

Code:
@Entity
@Table(name="address")
public class Address
{
   @Id
   private int aid;
   private String street;
   private String city;
   private String state;
   private String country;
}


The problem is when I want to retrieve all the user based on city, I am getting the following error.

org.hibernate.WrongClassException: Object with id: 1 was not of the specified subclass:User (loaded object was of wrong class class Patient)


The issue is when fetching the data hibernate check for the sub classes for Person table and wrongly take the Patient class instead of the User class. I create the criteria with User.class entity only,

I am using the criteria to query hibernate . Following is the code for retrieve the data

Code:
List <User> list = sessionFactory.openSession ().createCriteria ( User.class )
            .createAlias( "addresses","addr")
            .add(Restrictions.ilike("addr.city", "%" + streetName+"%"))            
            .list ();


Kindly anyone suggest that I am missing anything or any work around to solve this issues.

Thanks
Suersh T.


Top
 Profile  
 
 Post subject: Re: Hibernate inheritence issue
PostPosted: Wed Apr 10, 2013 9:13 am 
Newbie

Joined: Wed Mar 13, 2013 11:32 am
Posts: 16
Hi

You may be able to do this using as discriminator column in Person and add @DiscriminatorValue to Patient and User classes

Br

Jesper


Top
 Profile  
 
 Post subject: Re: Hibernate inheritence issue
PostPosted: Fri Apr 12, 2013 6:37 am 
Newbie

Joined: Tue Mar 19, 2013 5:46 am
Posts: 3
Hi Jesper,

Thanks For the reply.

But our database designed like that.

We are using "Table per subclass" strategy.

Thanks,
Suresh T.


Top
 Profile  
 
 Post subject: Re: Hibernate inheritence issue
PostPosted: Fri Apr 12, 2013 7:07 am 
Regular
Regular

Joined: Wed Apr 10, 2013 1:02 am
Posts: 50
Inheritance mapping seems to be fine its issue with address
Try using join table using many to many with unique=true

_________________
Regards
Akash Miital
http://akash.thegrassroots.co.in/hibernate/


Top
 Profile  
 
 Post subject: Re: Hibernate inheritence issue
PostPosted: Tue Apr 16, 2013 8:03 am 
Newbie

Joined: Tue Mar 19, 2013 5:46 am
Posts: 3
Hi Akash Miital,

Thanks for the reply.

Could you explain little more. I need to inherit patient and user from the person table. Our database is designed based on object oriented design and I can't change the design.

How a person have many to many relation ship with patient and user?

Sorry for this simple question because I am new to this kind of design.

Thanks
Suresh T


Top
 Profile  
 
 Post subject: Re: Hibernate inheritence issue
PostPosted: Wed Apr 17, 2013 1:59 am 
Regular
Regular

Joined: Wed Apr 10, 2013 1:02 am
Posts: 50
Hey man i was able to simulate the scenario.
However i have used XML hope you can have appropriate anno.

It is as per table per subclass
One patient can have Many address. as i said earlier you can do that by making many2many unique.

One more thing there is one more table added for person's address mapping hope your manager is ok with that.

here is the code.

Code:

package com.akash.model;

import java.util.Set;

public class Person {
   private int personId;
   private Set<Address> addresses;
   public int getPersonId() {
      return personId;
   }
   public void setPersonId(int personId) {
      this.personId = personId;
   }
   public Set<Address> getAddresses() {
      return addresses;
   }
   public void setAddresses(Set<Address> addresses) {
      this.addresses = addresses;
   }
   @Override
   public String toString() {
      return "Person [personId=" + personId + ", addresses=" + addresses
            + "]";
   }


}



Code:
/** @author Akash Mittal
    @version 1.0
   Project:Temp
   Package:com.akash.model
   File Nam:Address.java
    Last Updated 17-Apr-2013
    Purpose:
*/

package com.akash.model;

public class Address {
      private int aid;
      private String street;
       private String city;
      public int getAid() {
         return aid;
      }
      public void setAid(int aid) {
         this.aid = aid;
      }
      public String getStreet() {
         return street;
      }
      public void setStreet(String street) {
         this.street = street;
      }
      public String getCity() {
         return city;
      }
      public void setCity(String city) {
         this.city = city;
      }
      /**
       * @param aid
       * @param street
       * @param city
       */
      public Address(int aid, String street, String city) {
         super();
         this.aid = aid;
         this.street = street;
         this.city = city;
      }
      @Override
      public String toString() {
         return "Address [aid=" + aid + ", street=" + street + ", city="
               + city + "]";
      }
}


Code:
/** @author Akash Mittal
    @version 1.0
   Project:Temp
   Package:com.akash.model
   File Nam:Patient.java
    Last Updated 17-Apr-2013
    Purpose:
*/

package com.akash.model;

public class Patient extends Person {
   private int patientId;

   public int getPatientId() {
      return patientId;
   }

   public void setPatientId(int patientId) {
      this.patientId = patientId;
   }

   @Override
   public String toString() {
      return "Patient [patientId=" + patientId + ", getPersonId()="
            + getPersonId() + ", getAddresses()=" + getAddresses() + "]";
   }


   

}



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">
<!-- Generated Apr 17, 2013 10:12:02 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.akash.model.Person" table="PERSON">
        <id name="personId" type="int">
            <column name="PERSONID" />
            <generator class="assigned" />
        </id>
   
   
        <set name="addresses" table="PATIENTS_ADDRESS"  cascade="all">
            <key>
                <column name="PERSONID" />
            </key>
            <many-to-many class="com.akash.model.Address" column="AID" unique="true"/>
        </set>
   
         <joined-subclass name="com.akash.model.Patient">
          <key>
         <column name="PERSONID" />
         </key>
        <property name="patientId" type="int">
            <column name="PATIENTID" />
        </property>
         </joined-subclass>
    </class>
   
</hibernate-mapping>


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">
<!-- Generated Apr 17, 2013 10:12:02 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.akash.model.Address" table="ADDRESS">
        <id name="aid" type="int">
            <column name="AID" />
            <generator class="assigned" />
        </id>
        <property name="street" type="java.lang.String">
            <column name="STREET" />
        </property>
        <property name="city" type="java.lang.String">
            <column name="CITY" />
        </property>
    </class>
</hibernate-mapping>



Code:
/** @author Akash Mittal
    @version 1.0
   Project:Temp
   Package:com.akash.model
   File Nam:MainClient.java
    Last Updated 17-Apr-2013
    Purpose:
*/

package com.akash.model;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import com.akash.util.Hibernate4Util;

public class MainClient {
   
   public static void main(String[] args) {
      Hibernate4Util.currentSession().beginTransaction();
      Set<Address> addressSet = new HashSet<Address>();
      addressSet.add(new Address(12,"Noida","UP"));
      addressSet.add(new Address(13,"Ghaziabad","UP"));
      addressSet.add(new Address(14,"Viashali","UP"));
      Patient patient = new Patient();
      
      patient.setPatientId(13);
      patient.setPersonId(14);
      patient.setAddresses(addressSet);
      
      Hibernate4Util.currentSession().save(patient);
      Hibernate4Util.currentSession().getTransaction().commit();
   
      List<Patient> results = Hibernate4Util.currentSession().createQuery("from Patient ").list();
      for(Patient p : results)
         System.out.println(p);
      
   }

}


_________________
Regards
Akash Miital
http://akash.thegrassroots.co.in/hibernate/


Top
 Profile  
 
 Post subject: Re: Hibernate inheritence issue
PostPosted: Wed Apr 17, 2013 2:01 am 
Regular
Regular

Joined: Wed Apr 10, 2013 1:02 am
Posts: 50
Code:
select * from patient

select * from person

select * from address

select * from PATIENTS_ADDRESS


select * from address a where a.aid in (
select aid from PATIENTS_ADDRESS pa where pa.personid in ( 
select personid from patient)) and city like 'UP'

_________________
Regards
Akash Miital
http://akash.thegrassroots.co.in/hibernate/


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