Spring Data JPA:创建一个抽象存储库

Mar*_*itt 13 java spring spring-data spring-data-jpa

鉴于以下课程:

@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@DiscriminatorColumn(name="animalType",discriminatorType=DiscriminatorType.STRING)
@QueryExclude
public abstract class Animal  {}

@Entity
@DiscriminatorValue("dog")
public class Dog {}

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

有可能以某种方式配置JPA存储库Animal吗?

我试过了

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

然而,这失败了:

java.lang.IllegalArgumentException:不是托管类型:Animal

有没有办法配置这个?

我希望能够执行以下任务:

@Autowired
private AnimalRepository repository;

public void doSomething()
{
    Animal animal = repository.findById(123);
    animal.speak();
}
Run Code Online (Sandbox Code Playgroud)

kam*_*661 10

我有类似的错误.我通过添加我的实体类到我的persistence.xml文件的映射来解决它.

所以可能会在你的persistence.xml中添加这样的东西:

<persistence-unit>
...   
<class>yourpackage.Animal</class>
...
</persistence-unit>
Run Code Online (Sandbox Code Playgroud)

  • +1帮助我解决类似于发布的问题..感谢提醒.. (2认同)

CFL*_*eff 6

我遇到了这个问题,我找到了解决办法:你需要使用@MappedSuperclass OR @Inheritance,而不是两者都使用.Animal像这样注释你的类:

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

底层数据库方案将保持不变,现在您的通用AnimalRepository应该可以工作.持久性提供程序将执行内省并找出用于实际子类型的表.

  • 到目前为止唯一明智的答案.JPA注释是错误的.除了你所说的,如果每个类有一个表,为什么你需要一个鉴别器列?没有意义. (4认同)

Oli*_*ohm 2

我猜您正在运行 Hibernate 作为持久性提供程序,对吗?我偶然发现了 Hibernate 的这种情况的问题,因为针对 Hibernate 元模型的类型查找的行为与 JPA 中指定的内容不正确(有关详细信息,请参阅此错误)。所以看来你在这里有两个选择:

  1. 将抽象超类@Entity也更改为
  2. 切换到不同的持久提供者