JBoss.org Community Documentation
The EJB3 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.
This tutorial uses the table per class strategy to map an inheritance relationship of
org.jboss.tutorial.tableperinheritance.bean.Pet
, which is the base class for
org.jboss.tutorial.tableperinheritance.bean.Cat
and org.jboss.tutorial.tableperinheritance.bean.Dog
.
With the table per class strategy there is a table per class in the hierarchy, and each table has every single property that particular class will persist.
This is what the annotations look like for Pet:
@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Pet implements java.io.Serializable { ...
The subclass annotations look like this:
@Entity public class Dog extends Pet { ...
org.jboss.tutorial.tableperinheritance.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 findByWeight
method queries on Pet, either Dog or Cat instances can be returned.
The table mapping for this example looks like this:
create table CAT ( ID integer primary key, LIVES int NAME varchar, WEIGHT double ); create table DOG ( ID integer primary key, NUMBONES int NAME varchar, WEIGHT double );
The table per class strategy is less efficient than the single table strategy as the SQL query is more complicated.
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.
Because of a bug in HSQL, this tutorial does not work against the HSQL DB (which JBoss ships by default). Till this is fixed, running the client is not possible. Alternately, you can configure a datasource to use some other database and then use that datasource in the persistence.xml
From the command prompt, move to the "tableperinheritance" folder under the Section 1.3, “Set the EJB3_TUTORIAL_HOME”
Make sure the "default" server configuration of JBossAS-5.x is running
$ ant
$ 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.