Inheritance, Polymorphism, and Butler with no eyebrows.
dhinojosa Jun 28, 2006 2:49 AMSo for latest plea for help, I have a superclass entity (Animal), and two subclass entities (Dog, Cat) and an inheritance problem. The problem I have is in a stateful bean very similar to the example 'Messages' except mine is called "findAnimalLikeNameBean", and it runs queries on generalized animals. The problem I have with the following example is that the animal never gets outjected to the Animal field in my "findAnimalLikeNameBean", Please note the (//THIS ALWAYS RETURNS NULL") in the last code snippet of this post. I think I did a pretty good job scouring stuff to see what I did wrong but couldn't find anything (yet). Are there special cicumstances concerning inheritance and polymorphism?
@Entity(name="Animal") @Table(name="ag_animal") @Inheritance(strategy = InheritanceType.JOINED) @Name(value="animal") @Scope(value=ScopeType.SESSION) public class Animal implements Serializable { .... }
@Entity(name="Cat") @Table(name="ag_cat") @Inheritance(strategy = InheritanceType.JOINED) @Name(value="cat") public class Cat extends Animal implements Serializable { .... }
@Entity(name="Dog") @Table(name="ag_dog") @Inheritance(strategy = InheritanceType.JOINED) @Name(value="dog") public class Dog extends Animal implements Serializable { .... }
@Stateful @Name(value="findAnimalsLikeNameBean") @Scope(value=ScopeType.SESSION) public class FindAnimalsLikeNameBean extends AnimalQueryBean implements FindAnimalsLikeNameLocal{ @PersistenceContext(unitName="mypets", type=PersistenceContextType.EXTENDED) private EntityManager entityManager; private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } // public void setAnimal(Animal animal) { // this.animal = animal; // } // // public Animal getAnimal() { // return animal; // } @DataModel private List<Animal> animalList; @DataModelSelection @Out private Animal animal; @Logger private Log log; public void setAnimalList(List<Animal> animalList) { this.animalList = animalList; } public List<Animal> getAnimalList() { return animalList; } public String execute() { animalList = findLikeName(getName()); return "Success"; } @TransactionAttribute(value=TransactionAttributeType.REQUIRED) public List<Animal> findLikeName(String name) { String queryString = "SELECT p FROM Animal p " + "WHERE UPPER(p.name) LIKE UPPER(:name)) " + "ORDER BY p.name ASC"; Query query = entityManager.createQuery(queryString); query.setParameter("name", '%' + name + '%'); return createAnimalList(query.getResultList()); } public String select() { System.out.println(">>" + animal); //THIS ALWAYS RETURNS NULL if (animal != null) { if (animal instanceof Dog { return "Dog"; } if (animal instanceof Cat) { return "Cat"; } } return "Success"; } @Remove @Destroy public void destroy() {} }