-->
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.  [ 2 posts ] 
Author Message
 Post subject: Inheritance Problem in Hibernate
PostPosted: Tue Jun 20, 2006 2:43 pm 
Newbie

Joined: Wed Apr 26, 2006 2:43 pm
Posts: 6
Location: Bangalore
Hi Group

in hibernate i have two classes say Person and User .
now User class extends Person Class . now i have one method say

public static User getUserById(long id){

return (User)session.get(User.class,new Long(id));

}

this method is returns some time
1)Person Object
2) some time enhanced CGI Lib Person
3)some time enhanced CGI Lin User
4)some time User.

This is not a frequent behaviour .
98% time i retrive the correct Object but 2% i have wrong object as i have mentioned above :-(

is there anyone who has same problem.??


Top
 Profile  
 
 Post subject: Re: Inheritance Problem in Hibernate
PostPosted: Tue Jun 20, 2006 11:17 pm 
Beginner
Beginner

Joined: Fri Jun 02, 2006 1:14 am
Posts: 30
Yeah. As far as I can understand, this isn't a problem, it's a feature of Hibernate.

If you really need to emulate polymorphism with Hibernate, you can use the Visitor pattern:

Code:
public interface PersonVisitor {
  public Object visit(Person p);
  public Object visit(User u);
}

public class Person {
  // ...
  public Object accept(PersonVisitor v) {
    return v.visit(this);
  }
}

public class User extends Person {
  // ...
  public Object accept(PersonVisitor v) {
    return v.visit(this);
  }
}

// ...
Person somePerson = session.get(User.class,new Long(id));
String result = (String)somePerson.accept(new PersonVisitor() {
  public Object visit(Person p) { return "I'm a Person !"; }
  public Object visit(User u) { return "I'm a User ! Yar !"; }
});


The code above is roughly equivalent to the following code, which will NOT work with Hibernate:

Code:
Person somePerson = session.get(User.class,new Long(id));
String result;
if(somePerson instanceof User) {
  result = "I'm a User ! Yar !";
} else if(somePerson instanceof Person) {
  result = "I'm a Person !";
}


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