jpa inheritance and code reuse in service classes
I have a parent entity, Person, and two children entities : Caller and 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. In order to handle these objects i have some Service classes that handle database operations where i have methods like : getCallerById(); or getEmployeesByFirstName(). Also the save() methods are in these service classes. 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. 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
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
protected Person setCommonProperties(Person p){
p.setFoo(foo);
p.setBar(bar);
...
p.setWhatever(blahblah);
return p;
}
in your parentService( PersonService in your case)
And in your sub classes, (e.g. CallerService),
boolean save(){
Caller caller = new Caller();
caller = setCommonProperties(caller);
caller.setCallerPropertyA(...);
caller.setCallerPropertyB(...);
...
//save caller
return true or false;
}
精彩评论