假设我们有一个继承类型为[[TABLE_PER_CLASS的parent类A和child类B。
@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{
......
}
和存储库
@Repository public interface ARepository extends JpaRepository<A, Integer> { }
为什么当尝试从A查找findAll()对象时,我们也从B获取对象?
@RequestMapping(value = "/getAllA", method = RequestMethod.GET) public List<A> findAllA() { return aRepository.findAll(); }
@ Polymorphism(type = PolymorphismType.EXPLICIT)不会强制搜索仅返回对象吗?A
B
也是A
。您可以使用jpql作为解决方法,以指定要获取的具体结果类型:@Repository
public interface ARepository extends JpaRepository<A, Integer> {
@Query("select a from A a where type(a) = A")
List<A> findAll();
}