Java Reference
In-Depth Information
public List obtainProduct() {
TypedQuery<Object[]> qry = em.createQuery("select a.name, a.color " +
"from Factory f JOIN TREAT(f.product as WidgetA) a", Object[].class);
List data = new ArrayList();
if (!qry.getResultList().isEmpty()) {
List<Object[]> tdata = qry.getResultList();
for (Object[] t : tdata) {
HashMap resultMap = new HashMap();
resultMap.put("name", t[0]);
resultMap.put("color", t[1]);
data.add(resultMap);
}
}
return data;
}
To better understand this concept, let's talk a bit about the underlying database. The
Factory
entity class is the
object relational mapping for the
FACTORY
database table. The
Product
entity class is the object-relational mapping for
the
PRODUCT
database table. Lastly, the
WidgetA
entity class is a sub-type of the
Product
entity, so the
PRODUCT
table is
also utilized for storage of
WidgetA
object types. The overall structure of the
PRODUCT
database table is as follows:
CREATE TABLE PRODUCT (
ID NUMERIC PRIMARY KEY,
NAME VARCHAR(150),
PRODUCT_TYPE VARCHAR(50),
DESCRIPTION VARCHAR(2000),
COLOR VARCHAR2(100),
FACTORY_ID NUMERIC);
The
Product
entity class contains a few annotations that help to facilitate the entity relationship. First,
the
@Inheritence
annotation denotes that this entity is capable of
SINGLE_TABLE
inheritence. Next,
the
@DiscriminatorColumn
annotation declares the database column of
PRODUCT_TYPE
as a discriminator
column for the entity. This means that the
PRODUCT_TYPE
column is used to determine which entity sub-type object
to utilize for working with the data.
package org.javaee7.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;