我可以通过Spring Data JPA为MappedSuperClass的所有子项使用通用Repository吗? [英] Can I use a generic Repository for all children of a MappedSuperClass with Spring Data JPA?

查看:701
本文介绍了我可以通过Spring Data JPA为MappedSuperClass的所有子项使用通用Repository吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类结构:

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和使用 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

什么是最好的解决方案?



顺便说一句 - 动物 code>与其余的类一起列在 persistence.xml 中,所以这不是问题。

解决方案

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

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

不要担心,底层的数据库方案是一样的。现在,一般的 AnimalRepository 都可以工作。 Hibernate会做内省并找出哪个表用于实际的子类型。


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.

解决方案

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.

这篇关于我可以通过Spring Data JPA为MappedSuperClass的所有子项使用通用Repository吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆