如果你没有在数据库侧使用表继承(例如,带有decriminator列的超类表),AFAIK,并且基于阅读JPA教程的知识,则无法做到这一点(即,
@MappedSuperclass仅对抽象类使用注释)
映射的超类不能查询,也不能在EntityManager或Query操作中使用。你必须在EntityManager或Query操作中使用映射的超类的实体子类。映射的超类不能成为实体关系的目标
注意,JPA存储库抽象在幕后使用EntityManager。我做了一个简单的测试,你将得到(对于Hibernate实现)“
IllegalArgumentException : not an entity AbstractClass”
另一方面,如果确实使用表继承,则可以使用抽象类型。我知道你说过“只有很小的变化”(我想我的简短回答是我认为这是不可能的-可能是出于你猜测的原因),所以我想这个答案的其余部分是给其他打听者们的;- )
表继承策略的示例将是这样的(免责声明:这不是erd继承的正确可视化,但是MySQL Workbench不支持它,但是下面我将模型按照需要的方式进行了工程化,使其设计为MYSQL)。是)
哪里
CountryCatalog有对
AbstractCatalog表pk(id)的FK / PK参考。该
AbstractCatalog表具有一个
descriminatorColumn,将用于确定超型出现与哪个子类型相关。
在如何编码方面,它看起来像
@Entity@Inheritance(strategy = InheritanceType.JOINED)@DiscriminatorColumn(name="descriminatorColumn")@Table(name="AbstractCatalog")public abstract class AbstractCatalog { @Id private long id; ...}@Entity@Table(name = "CountryCatalog")public class CountryCatalog extends AbstractCatalog { // id is inherited ...}public interface AbstractCatalogRepository extends JpaRepository<AbstractCatalog, Long> {}@Repositorypublic class CountryCatalogServiceImpl implements CountryCatalogService { @Autowired private AbstractCatalogRepository catalogRepository; @Override public List<CountryCatalog> findAll() { return (List<CountryCatalog>)(List<?>)catalogRepository.findAll(); } @Override public CountryCatalog findOne(long id) { return (CountryCatalog)catalogRepository.findOne(id); } }如果你没有表继承,那么你要尝试执行的操作将无法正常工作。存储库的类类型必须是一个实体。如果你的表没有采用这种方式进行继承,则取决于你是否要更改表。不过,避免多个存储库可能会有点麻烦。



