I want to persist all variables in a superclass only from childclass
//This class is from an API, I cannot touch or change
class SuperClass {
private String name;
private String info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
@Entity
class ChildClass extends SuperClass {
@id
private long id;
}
I want the table to have these columns (id, name, info)
Is it doable? If yes, How?
If the accessors are not set as final
in the super class, you can override them in the child classes and add JPA annotations to the overridden accessor methods.
class SuperClass { public String getName() { ... } public String getInfo() { ... }
@Entity
class ChildClass extends SuperClass {
@Id
private long id;
public Long getId() { return id; }
@Access(AccessType.PROPERTY)
@Column(name = "name")
public String getName() { return super.getName(); }
@Access(AccessType.PROPERTY)
@Column(name = "info")
public String getInfo() { return super.getInfo(); }
}
class SuperClass { public String getName() { ... } public String getInfo() { ... }
@MappedSuperClass
class NamedModel extends SuperClass {
@Access(AccessType.PROPERTY)
@Column(name = "name")
public String getName() { return super.getName(); }
@Access(AccessType.PROPERTY)
@Column(name = "info")
public String getInfo() { return super.getInfo(); }
}
@Entity
class ChildClass extends NamedModel {
@Id
private long id;
}
I have created a sample application using your code. Download the application and run the integration tests as mvn clean test
and check the generated SQL to see the desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With