A class of objects derived from a hierarchy

In my project, I have a JPA hierarchy Location -> Site.

@Entity
@Table(name = "LOCATION")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="LOC_TYPE",discriminatorType=DiscriminatorType.STRING)
public class Location {
  ...
}

@Entity
@DiscriminatorValue("SI")
public class Site extends Location {
  ...
}

Now everyone Employeehas a list Locationassigned (even if, as far as I can tell, all such places are actually Site). In some part, I need a list Sitea Employee, which is assigned (note that the relation I defined was Locations).

With Hibernate 3.2, I can simply write a query for Locationand filter discriminant; return classes are instances of a more specific subclass, vg:

Query query = em.createQuery("SELECT loc FROM Location loc WHERE loc.type=\"SI\"");
List<Location> locations = (List<Location>) query.getResultList();
for (Location location : locations) {
  Site mySite = (Site) location;
  ...
}

, , JPA Hibernate. , , ).

, ?

, JPA 1 Hibernate 3.2

UPDATE:

, , , " ", . , disc , , Site .

Query query = em.createQuery("SELECT lo FROM Employee em JOIN em.location lo WHERE lo.disc = 'SI'");
List<Location> locations = (List<Location>) query.getResultList();
List<Site> site = new ArrayList<Site>();
for (Location location : locations) {
  if (location instanceof Site) {
    sites.add((Site) location);
  } else {
    log.warn("Found a Location that is not instance of Site");
  }
}

JPA, log.warn ? AFAIK, , Location, Site. , Location; ++.

+4
1

JPA, 2.0, TYPE(e). :

SELECT e FROM Employee e WHERE TYPE(e) IN (Exempt, Contractor)

JPA 2.0 (4.6.17.4. ):

. TYPE .


JPA.. , JPA, : ( JPA-) , Site, , Java (.. Site). , , Site (i.e fetchedEntity.getClass()==Site.class), 100% , fetchedEntity instanceof Site true.


. Hibernate , fetchedEntity.getClass() == Site.class true Hibernate (, , fetchedEntity instanceof Site).

+5

Source: https://habr.com/ru/post/1526559/


All Articles