1

我有两个具有各自接口的类,我想在它们之间创建 JPA@OneToOne关系。这失败了[class EmployeeImpl] uses a non-entity [class Adress] as target entity in the relationship attribute [field adress]

第一个接口/类:

public interface Employee {
  public long getId();
  public Adress getAdress();
  public void setAdress(Adress adress);
}

@Entity(name = "EmployeeImpl")
@Table(name = "EmployeeImpl")
public class EmployeeImpl implements Employee {

  @Id
  @Column(name = "employeeId")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  @OneToOne(cascade = CascadeType.PERSIST)
  private Adress adress;

  // snip, getters and setters
}

第二个接口/类:

public interface Adress {
  public long getId();
  public String getStreet();
  public void setStreet(String street);
}

@Entity(name = "AdressImpl")
@Table(name = "AdressImpl")
public class AdressImpl implements Adress {

  @Id
  @Column(name = "AdressId")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  @Column(name = "Street")
  private String street;

  // Snip getters and setters
}

persistence.xml 如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
  xmlns="http://java.sun.com/xml/ns/persistence" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="employee"
        transaction-type="RESOURCE_LOCAL">
        <class>EmployeeImpl</class>
        <class>AdressImpl</class>
        <properties>
            <property name="eclipselink.create-ddl-jdbc-file-name"
    value="create-matterhorn-employee.jdbc" />
            <property name="eclipselink.drop-ddl-jdbc-file-name" 
    value="drop-matterhorn-employee.jdbc" />
        </properties>
    </persistence-unit>

</persistence>

我缩短了包名称和导入等。尝试创建 EntityManagerFactory(您在其中移交持久性单元)时发生异常。我正在使用 Eclipse 链接 2.0.2。

4

2 回答 2

2

JPA 标准不允许接口字段(或接口字段的集合)是实体关系。一些 JPA 实现确实支持它(例如 DataNucleus JPA),但它是规范的供应商扩展。因此,您要么使用其中一种实现,要么更改您的模型(或添加额外的注释/XML 以定义实际存储在那里的类型)。

于 2013-11-15T09:30:12.463 回答
2

实际上 JPA​​ 确实允许这样的接口关系,但在这种情况下,您必须提供一个实体类来实现接口,在您的情况下,这将如下所示:

@OneToOne(targetEntity = AddressImpl.class)
private Adress adress;
于 2013-11-15T09:42:27.547 回答