Mat
Mat

Reputation: 1389

JPA : override mapping in child classes

I'm building an application based on an open source projet. This project defines its own model and jpa mapping, and I'd like to reuse this model. I'm using Hibernate, as in the original open source projet.

I have specificities in my project though, so I have custom classes extending the open source project classes with custom fields.

As an example :

Open source projet :

@Entity
public class AType {

    @ManyToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST})
    @JoinColumn(name = "btype_id")
    private BType bTypeField;


    @Column(name=basicField)
    private String basicField;

}

In my project

@Entity
public class CustomAType extends AType {

@ManyToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST})
@JoinColumn(name = "btype_id")
    private CustomBType customBTypeField;

}

In the CustomBType class I have specific attributes in addition to BType attribute.

To get an instance of CustomBType in CustomAType, I need to re-declare the mapping, and so JPA makes me mark one of the two mappings as read-only (updatable=false, insertable=false).

@ManyToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST})
@JoinColumn(name = "btype_id", insertable=false, updatable=false)
    private CustomBType customBTypeField;

}

As I get the open source project as a maven dep, I can't touch the mapping definition (or can I ?). So I maje my custom mapping read-only, and I can't insert custom objects anymore.

So my questions :

Upvotes: 0

Views: 331

Answers (1)

Alan Hay
Alan Hay

Reputation: 23226

As I get the open source project as a maven dep, I can't touch the mapping definition (or can I ?).

JPA allows overriding or disabling the JPA annotations in a class via an XML configuration file.

In answer to your question, you can then alter the mappings without touching the source:

https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/xml-overriding.html#d0e3768

Upvotes: 1

Related Questions