我可以为带有Spring数据JPA的MappedSuperClass的所有子类使用通用存储库吗?

我可以为带有Spring数据JPA的MappedSuperClass的所有子类使用通用存储库吗?,spring,hibernate,jpa,spring-data-jpa,mappedsuperclass,Spring,Hibernate,Jpa,Spring Data Jpa,Mappedsuperclass,鉴于以下类别结构: @MappedSuperclass @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public abstract class Animal {} @Entity public class Dog {} @Entity public class Cat {} 有了Spring数据JPA,是否可以在运行时使用通用的Animal存储库来持久化Animal,而不知道它是哪种动物 我知道我可以使用每个实体的存储库和

鉴于以下类别结构:

@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal  {}

@Entity
public class Dog {}

@Entity
public class Cat {}
有了Spring数据JPA,是否可以在运行时使用通用的
Animal
存储库来持久化
Animal
,而不知道它是哪种
动物

我知道我可以使用每个实体的存储库和
instanceof
这样做:

if (thisAnimal instanceof Dog) 
    dogRepository.save(thisAnimal);
else if (thisAnimal instanceof Cat)
    catRepository.save(thisAnimal);
} 
public interface AnimalRepository extends JpaRepository<Animal, Long> {}
但我不想求助于使用
instanceof
的糟糕做法

我尝试过使用这样的通用存储库:

if (thisAnimal instanceof Dog) 
    dogRepository.save(thisAnimal);
else if (thisAnimal instanceof Cat)
    catRepository.save(thisAnimal);
} 
public interface AnimalRepository extends JpaRepository<Animal, Long> {}
public interface AnimalRepository扩展了JpaRepository{}
但这会导致此异常:
不是托管类型:类动物
。我猜是因为
动物
不是一个
实体
,它是一个
映射超类

最好的解决方案是什么


顺便说一句,
Animal
persistence.xml
中列出了我的类中的其余部分,所以这不是问题。

实际上问题在于映射。您可以使用
@MappedSuperclass
@heritation
。两者加在一起没有意义。将您的实体更改为:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal  {}

别担心,底层数据库方案是相同的。现在,一个通用的
AnimalRepository
将起作用。Hibernate将进行内省,并找出实际子类型使用的表。

是否应将
动物
列为
persistence.xml中我的持久性单元中的一个类?您建议的更改导致了新的异常:
无法构建EntityManagerFactory
@CFL\u杰夫:通常我只依赖注释,所以我不确定。你能在某处发布完整的堆栈跟踪吗,包括由
引起的
?似乎除了这个问题之外,我还有其他问题。我相信你已经帮助我解决了手头的问题,我将致力于解决新问题。谢谢@杰夫:如果您有任何后续问题,请发布链接。