简体   繁体   中英

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?

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM