为什么即使子实体PolymorphismType为EXPLICIT,JPA方法也会返回子对象?

问题描述 投票:1回答:1

假设我们有一个继承类型为[[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

对象吗?
hibernate jpa inheritance table-per-class
1个回答
0
投票
这是因为B也是A。您可以使用jpql作为解决方法,以指定要获取的具体结果类型:

@Repository public interface ARepository extends JpaRepository<A, Integer> { @Query("select a from A a where type(a) = A") List<A> findAll(); }

© www.soinside.com 2019 - 2024. All rights reserved.