【问题标题】:JPA OneToOne - An internal error occurred accessing the primary key objectJPA OneToOne - 访问主键对象时发生内部错误
【发布时间】:2015-07-10 19:06:07
【问题描述】:

我正在尝试使用 JPA (EclipseLink) 为一个非常简单的 OneToOne 关系建模,但我得到了一个异常 java.lang.NoSuchFieldException 的描述“访问主键对象时发生内部错误”。

TableA 与 TableB 具有 OneToOne 关系。我需要在我的 TableA 实体上有一个 TableB 实体。

我的尝试

@NamedNativeQueries(... ommitted for breviety ...)
@Entity
@Table(name = "TableA")
@Cache(isolation = CacheIsolationType.ISOLATED)
public class TableA implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private TableA_Id id; //Code is part of the composite embeded

    @OneToOne
    @JoinColumn(name = "CODE", insertable = false, updatable = false)
    private TableB b;

    //getters + setters 

@NamedNativeQueries(... ommitted for breviety ...)
@Entity
@Table(name = "TableB")
@Cache(isolation = CacheIsolationType.ISOLATED)
public class TableB implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "CODE")
    private String code;

    @Column(name = "DESCRIPTION")
    private String description;

    //getters + setters 

例外:

Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: An internal error occurred accessing the primary key object [202].
Internal Exception: java.lang.NoSuchFieldException: b
Descriptor: RelationalDescriptor(com.foo.TableA --> [DatabaseTable(TableA)])

这可能值得注意; TableA和TableB上的代码之间没有定义外键;我没有能力改变它。

【问题讨论】:

    标签: java jpa


    【解决方案1】:

    您在表 A 中没有引用表 B 的外键,因此您不能像您所做的那样在表 A 上拥有连接列。

    @OneToOne
    @JoinColumn(name = "CODE", insertable = false, updatable = false)
    private TableB b;
    

    此语句要求连接列“代码”在表 A 中 - 但由于它在表 B 中,JPA 没有找到它,因此是例外。

    java.lang.NoSuchFieldException: b
    

    您需要将 TableB 实体作为 TableA 中的一个字段,并且您已声明不能将外键添加到 TableA。在这种情况下,这应该不是一个大问题,因为联接可以位于关系的任何一侧。

    鉴于您的限制,您可以将关系设为双向,拥有方为 TableB(包含连接的一方)和反方 TableA。

    尝试以下方法:

    @Entity
    @Table(name = "TableB")
    public class TableB ……
    //Owning side of the relationship with the @JoinColumn annotation.
        @OneToOne
        @JoinColumn(name = "CODE", insertable = false, updatable = false)
        private TableA tableA;
    
    @Entity
    @Table(name = "TableA")
    public class TableA ……..
    //Inverse side of the relationship with the MappedBy attribute.
        @OneToOne(MappedBy = tableA)
        private TableB tableB;
    

    【讨论】:

      猜你喜欢
      • 2012-07-15
      • 2016-05-26
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      相关资源
      最近更新 更多