【发布时间】:2023-03-31 00:10:01
【问题描述】:
给定以下类结构:
@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
@Entity
public class Dog {}
@Entity
public class Cat {}
使用 Spring Data JPA,是否可以使用通用 Animal 存储库在运行时持久化 Animal,而不知道它是哪种类型的 Animal?
我知道我可以使用 Repository-per-entity 并使用 instanceof 来做到这一点,如下所示:
if (thisAnimal instanceof Dog)
dogRepository.save(thisAnimal);
else if (thisAnimal instanceof Cat)
catRepository.save(thisAnimal);
}
但我不想诉诸使用 instanceof 的坏习惯。
我尝试过使用这样的通用存储库:
public interface AnimalRepository extends JpaRepository<Animal, Long> {}
但这会导致此异常:Not an managed type: class Animal。我猜是因为Animal 不是Entity,而是MappedSuperclass。
什么是最好的解决方案?
顺便说一句 - Animal 与我在 persistence.xml 中的其他课程一起列出,所以这不是问题。
【问题讨论】:
标签: spring hibernate jpa spring-data-jpa mappedsuperclass