首页 > 解决方案 > 为什么休眠 PolymorphismType.EXPLICIT 注释在 JPA findAll() 搜索中返回父级的子级?

问题描述

假设我们有一个类 A 和一个继承类型为TABLE_PER_CLASS的类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 中查找所有对象时,我们也从 B 中获取对象?

 @RequestMapping(value = "/getAllA", method = RequestMethod.GET)
 public List<A> findAllA() {
    return aRepository.findAll();
}

@Polymorphism(type = PolymorphismType.EXPLICIT) 不应该强制搜索只返回A对象吗?

标签: javahibernateinheritancejpqlhibernate-mapping

解决方案


这是因为B也是一个A. 您可以使用 jpql 作为解决方法来指定要获取的具体结果类型:

@Repository
public interface ARepository extends JpaRepository<A, Integer> {

    @Query("select a from A a where type(a) = A")
    List<A> findAll();

}

根据对这个问题的回答,如果没有注释@DiscriminatorColumn,这将不起作用。@DiscriminatorValue


推荐阅读