mike mike - 5 months ago 27
Java Question

Is there a way to extend a JPA entity to add relationships?

So I've got a property class

public class Property {
@Id
@Column(name="PROPERTY_ID")
private Long propertyId;

@Column(name="NAME")
private String name;

@Column(name="TYPE_CODE")
private Integer typeCode;

...getters and setters...
}


That I want to use to get limited information for requests that pull ALL the properties in my database.

But I also want a class that utilizes the DB constraints to make relationships

public class ExportProperty extends Property {

@ManyToOne
@JoinColumn(name="TYPE_CODE")
private ExportPropertyType type;

@OneToMany(mappedBy="property", fetch=FetchType.EAGER)
private Set<ExportPropertyPhoneNumber> phoneNumbers;

...getters and setters...
}


That I can use to get ALL data for a single property.

Is this possible? Or do I need to rethink my strategy?

Answer

Thanks to Guillaume F. I was able to find a solution.

I have a common supertype class that includes any common fields

@MappedSuperclass
public class PropertySuper {
    @Id
    @Column(name="PROPERTY_ID")
    private Long propertyId;

    @Column(name="NAME")
    private String name;

    ...getters and setters...
}

A class that has just the data in the Property table

@Entity
@Table(name = "PROPERTY")
public class Property extends PropertySuper {

    @Column(name="TYPE_CODE")
    private Integer typeCode;

    ...getters and setters...
}

and a class that has all of the JPA links

@Entity
@Table(name = "PROPERTY")
public class FullProperty extends PropertySuper {

    @ManyToOne
    @JoinColumn(name="TYPE_CODE")
    private FullPropertyType type;

    @OneToMany(mappedBy="property", fetch=FetchType.EAGER)
    private Set<FullPropertyPhoneNumber> phoneNumbers;

    ...getters and setters...
}
Comments