JBoss.org Community Documentation
The EJB specification allows you to define entities that inherit from one another. The inheritance relationships can be reflected in queries as well. So, if you queried based on the base class, the query is polymorphic.
The tutorial example uses the single table strategy to map an inheritance relationship of org.jboss.tutorial.singleinheritance.bean.Pet
,
which is the base class for org.jboss.tutorial.singleinheritance.bean.Cat
and org.jboss.tutorial.singleinheritance.bean.Dog
.
With the single table strategy, the entire class hierarchy is persisted in one big single table. A discriminator column is required to
differentiate between which class type is persisted in a particular row. This is what the annotations look like for Pet.
@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "ANIMAL_TYPE", discriminatorType = DiscriminatorType.STRING) public class Pet implements java.io.Serializable { }
The @DiscriminatorColumn
specifies the column that will hold the type of the persisted entity.
For subclasses, they must define the value of the discriminator column that will identify the class.
Here's the Dog entity which extends Pet:
@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue("DOG") public class Dog extends Pet { }
org.jboss.tutorial.singleinheritance.bean.PetDAOBean
stateless EJB wraps some polymorphic queries.
public List findByWeight(double weight) { return manager.createQuery("from Pet p where p.weight < :weight").setParameter("weight", weight).getResultList(); }
Even though the <listing>findByWeight</listing> method queries on Pet, either Dog or Cat instances can be returned.
The table mapping for this example looks like this:
create table PET ( ID integer primary key, ANIMAL_TYPE varchar, NAME varchar, WEIGHT double, LIVES int, NUMBONES int );
To build and run the example, make sure you have installed JBoss 5.x. See the Section 1.1, “JBoss Application Server 5.x” for details.
From the command prompt, move to the "singleinheritance" folder under the Section 1.3, “Set the EJB3_TUTORIAL_HOME”
Make sure your JBossAS-5.x is running
$ ant $ ant run run: [java] Sox [java] Junior
$ mvn clean install -PRunSingleTutorial
You can view the tables created by JBoss by going to the
Hypersonic Service,
scrolling down to the startDatabaseManager
button and clicking it.
A Hypersonic SQL window will be minimized, but you can open it up to look at the tables and do queries.