Can I use a generic Repository for all children of a MappedSuperClass with Spring Data JPA?

你离开我真会死。 提交于 2019-12-23 07:24:39

问题


Given the following class structure:

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

@Entity
public class Dog {}

@Entity
public class Cat {}

With Spring Data JPA, is it possible to use a generic Animal Repository to persist an Animal at runtime without knowing which kind of Animal it is?

I know I can do it using a Repository-per-entity and by using instanceof like this:

if (thisAnimal instanceof Dog) 
    dogRepository.save(thisAnimal);
else if (thisAnimal instanceof Cat)
    catRepository.save(thisAnimal);
} 

but I don't want to resort to the bad practice of using instanceof.

I've tried using a generic Repository like this:

public interface AnimalRepository extends JpaRepository<Animal, Long> {}

But this results in this Exception: Not an managed type: class Animal. I'm guessing because Animal is not an Entity, it's a MappedSuperclass.

What's the best solution?

BTW - Animal is listed with the rest off my classes in persistence.xml, so that's not the problem.


回答1:


Actually the problem is with your mapping. You either use @MappedSuperclass or @Inheritance. Both together don't make sense. Change your entity to:

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

Don't worry, the underlying database scheme is the same. Now one, general AnimalRepository will work. Hibernate will do the introspection and find out which table to use for an actual subtype.



来源:https://stackoverflow.com/questions/14286841/can-i-use-a-generic-repository-for-all-children-of-a-mappedsuperclass-with-sprin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!