java - 为什么休眠 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对象吗?
解决方案
这是因为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
推荐阅读
- swift - Swift 无法从 Swift.X 转换为 Swift.X.Type
- linear-programming - 或工具 - 使决策变量尽可能靠近并远离边界
- java - 为什么扫描仪会给出 java.util.InputMismatchException?
- javascript - JSForce 与 Angular 的集成编译失败。在“./connection”中找不到导出“ConnectionConfig”
- swagger-ui - 从干净的 UI 测试在 dropwizard 中创建的 API,因为 swagger 集成很糟糕
- python - Catboost python 功能重要性缺少 1 个必需的位置参数:“值”
- concurrency - 在 erlang 中轮询接收块是一种好的做法吗?
- database - 后台laravel中impelement数据库密集操作
- google-cloud-platform - 如何将 Data Fusion 连接到 Cloud SQL 代理
- php - PHP 将十六进制转换为 Base32 和反之亦然