【问题标题】:Can I use a generic Repository for all children of a MappedSuperClass with Spring Data JPA?我可以使用 Spring Data JPA 为 MappedSuperClass 的所有子级使用通用存储库吗?
【发布时间】:2023-03-31 00:10:01
【问题描述】:

给定以下类结构:

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

@Entity
public class Dog {}

@Entity
public class Cat {}

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

我知道我可以使用 Repository-per-entity 并使用 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

什么是最好的解决方案?

顺便说一句 - Animal 与我在 persistence.xml 中的其他课程一起列出,所以这不是问题。

【问题讨论】:

    标签: spring hibernate jpa spring-data-jpa mappedsuperclass


    【解决方案1】:

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

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

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

    【讨论】:

    • 是否应该将Animal 列为persistence.xml 中我的持久性单元中的一个类?您建议的更改导致新异常:Unable to build EntityManagerFactory
    • @CFL_Jeff:通常我只依赖注释,所以我不确定。你能在某处发布完整的堆栈跟踪,包括Caused by吗?
    • 似乎除了这个问题我还有其他问题。我相信你已经帮助我解决了手头的问题,我会努力解决新的问题。谢谢!
    • @CFL_Jeff:如果您有任何问题,请发布后续问题的链接。
    猜你喜欢
    • 2018-06-15
    • 2013-08-23
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2015-07-13
    • 2015-02-17
    • 2022-01-12
    相关资源
    最近更新 更多