我可以使用Spring Data JPA为MappedSuperClass的所有子项使用通用存储库吗?

CFL*_*eff 10 spring hibernate jpa mappedsuperclass spring-data-jpa

给定以下类结构:

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

@Entity
public class Dog {}

@Entity
public class Cat {}
Run Code Online (Sandbox Code Playgroud)

使用Spring Data JPA,是否可以使用通用Animal存储库Animal在运行时持久保存而不知道Animal它是哪种类型?

我知道我可以使用每个实体的存储库并使用instanceof这样的方式来实现:

if (thisAnimal instanceof Dog) 
    dogRepository.save(thisAnimal);
else if (thisAnimal instanceof Cat)
    catRepository.save(thisAnimal);
} 
Run Code Online (Sandbox Code Playgroud)

但我不想诉诸于使用的不良做法instanceof.

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

public interface AnimalRepository extends JpaRepository<Animal, Long> {}
Run Code Online (Sandbox Code Playgroud)

但这导致了这个例外:Not an managed type: class Animal.我猜是因为Animal不是Entity,它是一个MappedSuperclass.

什么是最好的解决方案?

顺便说一句 - Animal列出其余的我的课程persistence.xml,所以这不是问题.

Tom*_*icz 5

实际上,问题出在您的映射上。您可以使用@MappedSuperclass @Inheritance。两者都没有意义。将您的实体更改为:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal  {}
Run Code Online (Sandbox Code Playgroud)

不用担心,底层数据库方案是相同的。现在,AnimalRepository将通用。Hibernate将进行自省,并找出用于实际子类型的表。