简体   繁体   中英

Should a Java persistence entity have a common parent as the regular object?

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

我最终无法执行此操作,因为它导致了我的旧序列化对象的问题,并决定在课堂上尽可能多地进行分解。

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