给定以下类结构:
@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
@Entity
public class Dog {}
@Entity
public class Cat {}
With Spring数据JPA,是否可以使用通用的Animal
用于持久保存的存储库Animal
在运行时不知道是哪种Animal
这是?
我知道我可以使用每个实体的存储库并使用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
.
最好的解决方案是什么?
BTW - Animal
与我的课程的其余部分一起列出persistence.xml
,所以这不是问题。
其实问题出在你的映射上。你要么使用@MappedSuperclass
or @Inheritance
。两者放在一起就没有意义了。将您的实体更改为:
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
不用担心,底层数据库方案是相同的。现在一位,将军AnimalRepository
将工作。 Hibernate 将进行内省并找出哪个表用于实际的子类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)