给定以下类结构:
@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
与我的其他类(class)一起在 persistence.xml
中列出,所以这不是问题。
最佳答案
实际上问题在于您的映射。您可以使用 @MappedSuperclass
或 @Inheritance
.两者一起没有意义。将您的实体更改为:
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
不用担心,底层数据库方案是一样的。现在一、将军
AnimalRepository
将工作。 Hibernate 将进行自省(introspection)并找出用于实际子类型的表。
关于spring - 我可以使用 Spring Data JPA 为 MappedSuperClass 的所有子级使用通用存储库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14286841/