Let's say we have a parent class A and a child class B with the inheritance type TABLE_PER_CLASS.
@Entity(name = "A")
@Table(name = "A")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class A{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
...........
}
@Entity(name = "B")
@Table(name = "B")
@Polymorphism(type = PolymorphismType.EXPLICIT)
public class B extends A{
......
}
And the repository
@Repository
public interface ARepository extends JpaRepository<A, Integer> {
}
Why is when trying to findAll() objects from A we get the objects from B too?
@RequestMapping(value = "/getAllA", method = RequestMethod.GET)
public List<A> findAllA() {
return aRepository.findAll();
}
Shouldn't the @Polymorphism(type = PolymorphismType.EXPLICIT) force the search to return only A objects?
It's because B
is also an A
. You can use jpql as a workaround to specify the concrete result type you want to fetch:
@Repository
public interface ARepository extends JpaRepository<A, Integer> {
@Query("select a from A a where type(a) = A")
List<A> findAll();
}
According to answers to this question this will not work without @DiscriminatorColumn
and @DiscriminatorValue
annotations.