我可以通过Spring Data JPA为MappedSuperClass的所有子项使用通用Repository吗? [英] Can I use a generic Repository for all children of a MappedSuperClass with Spring Data JPA?
问题描述
pre $ @ $ $ $ $ @ @ $ $ $ $ b @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
@ Entity
public class Dog {}
@ Entity
public class Cat {}
使用 Spring Data JPA ,是否可以使用通用的 我知道我可以使用Repository-per-entity和使用 但我不想诉诸使用 我试过使用这样的通用库: 但是这会导致以下异常: 什么是最好的解决方案? 顺便说一句 - 其实问题出在你的映射上。您可以使用 不要担心,底层的数据库方案是一样的。现在,一般的 Given the following class structure: With Spring Data JPA, is it possible to use a generic I know I can do it using a Repository-per-entity and by using but I don't want to resort to the bad practice of using I've tried using a generic Repository like this: But this results in this Exception: What's the best solution? BTW - Actually the problem is with your mapping. You either use Don't worry, the underlying database scheme is the same. Now one, general 这篇关于我可以通过Spring Data JPA为MappedSuperClass的所有子项使用通用Repository吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!动物
存储库在运行时保存动物
而不知道哪种
instanceof
来完成这项工作:
if(thisAnimal instanceof Dog)
dogRepository.save(thisAnimal);
else if(thisAnimal instanceof Cat)
catRepository.save(thisAnimal);
}
instanceof
。
public interface AnimalRepository扩展JpaRepository< Animal,Long> {}
不是托管类型:class动物
。我猜是因为 Animal
不是实体
,它是 MappedSuperclass $ c
动物 code>与其余的类一起列在
persistence.xml
中,所以这不是问题。
@MappedSuperclass
或 @Inheritance
。两者在一起都没有意义。将实体更改为:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
AnimalRepository
都可以工作。 Hibernate会做内省并找出哪个表用于实际的子类型。@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
@Entity
public class Dog {}
@Entity
public class Cat {}
Animal
Repository to persist an Animal
at runtime without knowing which kind of Animal
it is? instanceof
like this: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
. I'm guessing because Animal
is not an Entity
, it's a MappedSuperclass
.Animal
is listed with the rest off my classes in persistence.xml
, so that's not the problem.@MappedSuperclass
or @Inheritance
. Both together don't make sense. Change your entity to:@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
AnimalRepository
will work. Hibernate will do the introspection and find out which table to use for an actual subtype.