I'm cleaning up some code, and I have a class with an entity that implement a lot of the same behaviour. Should I combine that behaviour into a parent that both inherit or is there a reason to keep them separate?
(There are also some transfers of data between the entity and normal class that would be made easier if I could upcast to a method that would pass data between them)
Also what to do about the database specific additions to the shared variable?
For example, in the below code, should I create a class `MyBase` and extract `prop1` plus its getters and setters to the `MyBase` class and then have `MyObject` and `MyObjectEntity` both extend `MyBase`?
Normal:
public class MyObject {
private String prop1;
public MyObject() {}
public String getProp1() {
return prop1;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
public void doSomethingNormal() {
//Do something normal
}
}
Entity:
@Entity
public class MyObjectEntity
{
@Column(unique = true, nullable = false)
private String prop1;
public MyObjectEntity() {}
public String getProp1() {
return prop1;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
public void doSomethingEntity() {
//Do something entity like
}
}
Totally depends. Maybe an interface is more appropriate, and a property-copy util like Commons' BeanUtils. Hard to say with the info given. Using a normal class as an entity base class can cause a different set of problems depending on persistence framework, how/if reflection is used, etc.
以上就是Should a Java persistence entity have a common parent as the regular object?的详细内容,更多请关注web前端其它相关文章!