简体   繁体   English

服务类中的jpa继承和代码重用

[英]jpa inheritance and code reuse in service classes

I have a parent entity, Person, and two children entities : Caller and Employee. 我有一个父实体,Person和两个子实体:Caller和Employee。 The two children share a lot of fields so i implemented JPA inheritance with single table strategy and discriminator column.So far so good. 这两个孩子共享许多字段,因此我使用单表策略和区分符列实现了JPA继承。到目前为止,一切都很好。 In order to handle these objects i have some Service classes that handle database operations where i have methods like : getCallerById(); 为了处理这些对象,我有一些服务类来处理数据库操作,其中我有如下方法:getCallerById(); or getEmployeesByFirstName(). 或getEmployeesByFirstName()。 Also the save() methods are in these service classes. 同样,save()方法也位于这些服务类中。 The problem is that when i want to save an employee or an caller i got a lot of duplicate code (for all the shared properties), so in order to prevent this i created a 3rd service: PersonService() in order to handle the common functionality. 问题是,当我想保存一名雇员或呼叫者时,我得到了很多重复的代码(用于所有共享属性),因此为了防止这种情况,我创建了第三项服务:PersonService()以处理常见问题功能。 But now i do not know how to use this service in order to reuse as much code as i can. 但是现在我不知道如何使用此服务来重用尽可能多的代码。 Maybe in the PersonService() to have something like 也许在PersonService()中有类似

public Boolean save(Person p){
    if (p instanceOf Caller){
       Caller c = new Caller();
       c.setCallerSpecificProperty("XXX");
    }

    if (p instanceOf Employee){
      Employee c = new Employee()
      c.setEmployeeSpecificProperty("YYY");
    }

    c.setOtherCommonParameter("ccc");
   //............
}

or how do you advise me to handle this problem??? 或您如何建议我处理此问题??? Thanks 谢谢

if your problem is just to set the 100 commonProperties of Person, you can add helper method, say 如果您的问题只是设置Person的100个commonProperties,则可以添加helper方法,例如

 protected Person setCommonProperties(Person p){
p.setFoo(foo);
p.setBar(bar);
...
p.setWhatever(blahblah);

return p;
}

in your parentService( PersonService in your case) 在您的parentService中(在您的情况下为PersonService)

And in your sub classes, (eg CallerService), 在子类中(例如CallerService),

   boolean save(){
     Caller caller = new Caller();
    caller = setCommonProperties(caller);
    caller.setCallerPropertyA(...);
    caller.setCallerPropertyB(...);

    ...

    //save caller
return true or false;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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