Reputation: 237
I have two classes with their respective interfaces between which I want to create a JPA @OneToOne
Relation. This fails with [class EmployeeImpl] uses a non-entity [class Adress] as target entity in the relationship attribute [field adress]
.
First Interface / Class:
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
}
Second Interface / Class:
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
}
The persistence.xml looks like this:
<?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>
I shortened out package names and imports and such. Exception occurs when trying to create the EntityManagerFactory (where you hand over the persistence unit). I am using eclipse link 2.0.2.
Upvotes: 1
Views: 337
Reputation: 4454
Actually JPA does allow such interface relationships, but in this case you have to provide an entity class implementing the interface, in you case this will look as follows:
@OneToOne(targetEntity = AddressImpl.class)
private Adress adress;
Upvotes: 2
Reputation: 15577
JPA standard does not allow for interface fields (or Collection of interface fields) being entity relationships. Some JPA implementations do support it (e.g DataNucleus JPA), but its a vendor extension to the spec. Consequently you either use one of those implementations or change your model (or add extra annotations/XML to define what type is actually stored there).
Upvotes: 2