如何在JPA编程模型中使用继承?

时间:2013-12-11 00:33:39

标签: jpa eclipselink

我正在尝试使用JPA 2.1实现此模型。我正在使用 JSR 338 规范和参考实现 Eclipselink

只保留第三级实体和关联类。 enter image description here

@MappedSuperclass

public abstract class PessoaMaster implements Serializable {

private static final long serialVersionUID = 1L;
private long id;
private List<Telefone> telefones;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID_Pai", unique=true, nullable=false)
public long getId() {
    return id;
}
public void setId(long identificador) {
    id = identificador;
}
/**
 * @return the telefones
 */
@OneToMany
public List<Telefone> getTelefones() {
    return telefones;
}

/**
 * @param telefones the telefones to set
 */
public void setTelefones(List<Telefone> telefones) {
    this.telefones = telefones;
}
}

我可以在这里用而不是继承MappedSuperclass吗?

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)    
public abstract class FornecedorSuper extends PessoaMaster{

    //attributes and relationships

}

持久的实体。

public class FornecedorPecas extends FornecedorSuper {

private Double Valor;

@Column(name="ValorPeca")
public Double getValor() {
    return Valor;
}

public void setValor(Double valor) {
    Valor = valor;
}
}

有必要使用@ Entity标记FornecedorPeças类吗?

当我在FornecedorSuper中插入MappedSuperclass时。抛出此异常:

Exception in thread "main" Local Exception Stack: Exception [EclipseLink-30005] (Eclipse Persistence Services - .5.0.v20130507-3faac2b):org.eclipse.persistence.exceptions.PersistenceUnitLoadingException Exception Description: An exception was thrown while searching for persistence archives ith ClassLoader: sun.misc.Launcher$AppClassLoader@affc70 Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [modelo] failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class br.miltex.dominio.model.FornecedorPecas] has no primary key specified. It should define either an @Id, @EmbeddedId or an @IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.

2 个答案:

答案 0 :(得分:1)

  

Q1。我可以在这里使用而不是继承MappedSuperclass吗?

虽然我没有在规范中找到任何示例,但JPA规范说:

  

MappedSuperclass注释指定了一个其映射的类   信息应用于从其继承的实体。映射   超类没有为它定义单独的表。

所以它说映射信息应用于实体,但它没有说MappedSuperclass不允许扩展另一个MappedSuperclass,所以我相信你可以在你的{{1}中使用} FornecedorSuper注释的类。

  

Q2。有必要使用@ Entity标记FornecedorPeças类吗?

是的,这是必要的。

答案 1 :(得分:0)

我在属性和方法上添加了注释。出于这个原因,发生了异常。

感谢您的帮助。