title: Selecting MappedSuperclass from the database (Hibernate)
body: <h1>Problem</h1>
  
  <p>I have a <code>@MappedSuperclass</code> called Data as the parent of every Entity in my database. It contains common attributes like Id etc. I then have an entity that extends Data which is also a <code>@MappedSuperclass</code> due to common functionality of its subclasses. The mapping in my database is correct.</p>
  
  <p>Here is an example of my hierarchy</p>
  
  <pre>
  @MappedSuperclass
  Data  
   |  @MappedSuperclass
   +- Employee  
   |      |  @Entity
   |      +- FullTimeEmployee
   |      |  @Entity
   |      +- PartTimeEmployee
   |  @Entity
   +- Store
  </pre>
  
  <p>And the tables are correctly mapped:</p>
  
  <pre>
  FullTimeEmployee  
  PartTimeEmployee  
  Store
  </pre>
  
  <p>Is there anyway to query the database for all Employee subclasses (FullTimeEmployee, PartTimeEmployee) as instances of Employee without referring the name of the subclasses in the query?</p>
  
  <p>Something like</p>
  
  <pre><code>List&lt;Employee&gt; allEmployees = getAllEmployees();
  </code></pre>
  
  <p>The idea is that whenever I decide to create another subclass of Employee (i.e. AllDayEmployee) I will not have to change the query to include the name.</p>
  
  <hr>
  
  <h1>Solution</h1>
  
  <p>So, as <a href="https://stackoverflow.com/questions/1427439/selecting-mappedsuperclass-from-the-database-hibernate/1427490#1427490">Gregory</a> correctly pointed out, this is not possible with <code>@MappedSuperclass</code>. So I changed it into @Entity and, since I wanted to preserve a table for each subclass I used <code>InheritanceType.JOINED</code>. </p>
  
  <p>So the above hierarchy is now</p>
  
  <pre>
  @MappedSuperclass
  Data  
   |  @Entity
   |  @Inheritance(strategy=InheritanceType.JOINED)
   +- Employee  
   |      |  @Entity
   |      +- FullTimeEmployee
   |      |  @Entity
   |      +- PartTimeEmployee
   |  @Entity
   +- Store
  </pre>
  
  <p>And the tables are still:</p>
  
  <pre>
  FullTimeEmployee  
  PartTimeEmployee  
  Store
  </pre>
  
  <p>So now, to get all Employees I simply call:</p>
  
  <pre><code>entityManager.createQuery("from Employee").getResultList();
  </code></pre>