DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ratn has posted 5 posts at DZone. View Full User Profile

Use Of Visitor Pattern To Visit Hibernate Proxy

06.06.2010
| 5588 views |
  • submit to reddit
        You can not use instanceof operator on Hibernate Proxy even if the proxy is initialised.You should use Visitor in that case .For example 

There is charity fund which accepts donation from Party (it may be Group also).After receiving donation it would send thank mail to Party or in case of Group ,it sends thanks mail to everyone in group.  

  @Entity
  //set inheritance type 
  public class Party {
    private String name;
    public String getName() {
       return name;
    }
  }
  @Entity 
  public class Group extends Party  {
  List<Party> getGroupMembers() {
    return groupMembers;
  }
  }

  @Entity
  public class Donation {
    //fetchType is set to lazy 
    private Party;
    public Party getParty {
       return Party;
    }
  }

Now lets see charity Service -- 
public class CharityService {
    public void sendThanksMailToParty(Donation donation){
      Party party = donation.getParty();
      //instaneof operator would alsways return false ,even if 
      //Party is really Group
      //because Proxy is subclass of Party, it does not know about Group
      //Proxy has a target and it delegates method calls to it.
      if(party instanceOf Group){
      //send email to every group member 
      }
    }
}

so how to make it work ,lets use vistor pattern 

 
 public interface Visitable {
    public void accept(Visitor visitor);
 }
 public interface Visitor {
   public void visit(Party party);
   public void visit(Group group);
 }

 public class DefaultVisitor extends Visitor {
   public void visit(Party party){};
   public void visit(Group group){};
 }
 
@Entity
  //set inheritance type 
  public class Party implements Visitable{
    private String name;
    public String getName() {
       return name;
    }
   public void accept(Visitor visitor){
     visitor.visit(this);
   }
  }

 @Entity 
  public class Group extends Party  implements Visitable{
  List<Party> getGroupMembers() {
    return groupMembers;
  }
  public void accept(Visitor visitor){
     visitor.visit(this);
   }
  }


Now lets see charity service again --- 

Now lets see charity Service  again -- 
public class CharityService {
    public void sendThanksMailToParty(Donation donation){
      Party party = donation.getParty();
      party.accept(new DefaultVisitor(){
           public void visit(Group group){
               List<Party> parties= group.getGroupMembers;
               //now send email to each member of party
            }
      });
    }
}