JPA继承要求子类中的ID [英] JPA Inheritance demands ID in subclass

查看:146
本文介绍了JPA继承要求子类中的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的jpa域模型有问题。我只是尝试使用简单的继承,我使用一个简单的Person基类和Customer子类。根据官方文档(JPA和EclipseLink),我只需要基类中的ID属性/列。 但是当我运行我的测试时,我总是收到错误,告诉我客户没有@Id?

I have a problem with my jpa domain model. I am just trying to play around with simple inheritance for which I use a simple Person base-class and and a Customer subclass. According to the official documentation (both, JPA and EclipseLink) I only need the ID-attribute/column in the base-class. But when I run my tests, I always get an error telling me that Customer has no @Id?

首先我认为问题在于id属性的可见性,因为它首先是私有的。但即使我将其更改为受保护(因此子类具有直接访问权限),它也无法正常工作。

First I thought the problem lies in the visibility of the id-attribute, because it was private first. But even after I changed it to protected (so the subclass has direct access) it isnt working.

人:

@Entity @Table(name="Persons")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "TYPE")
public class Person {

    @Id
    @GeneratedValue
    protected int id;
    @Column(nullable = false)
    protected String firstName;
    @Column(nullable = false)
    protected String lastName;

客户:

@Entity @Table(name = "Customers")
@DiscriminatorValue("C")
public class Customer extends Person {

    //no id needed here

我的想法和资源都用完了。这应该是一个相当简单的问题,但我只是没有看到它。

I am running out of ideas and resources to look at. It should be a rather simple problem, but I just dont see it.

推荐答案

我通过创建MappedSuperclass来解决它自己p>

I solved it myself by creating a MappedSuperclass

@MappedSuperclass
public abstract class EntityBase{
   @Id
   @GeneratedValue
   private int id;

   ...setter/getter
}

所有实体继承自这个类。我仍然想知道为什么这些教程不提这个,但是JPA 2实现可能会变得更好。

All entities are inheriting from this class. I am still wondering why the tutorials dont mention this, but maybe it gets better with the JPA 2 implementations.

这篇关于JPA继承要求子类中的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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