My Java project uses JPA as a persistence solution. As I read more and more JPA tutorials and guides I find (for the sake of simplicity, maybe) that every writer uses the entity classes as their model classes. That's obviously a poor design choice with regards to code extensibility and maintainability: a decision to change the persistence solution would imply a complete refactoring (or rewriting) of the whole model.
Thing is, rewriting model classes corresponding to each entity class feels out of place and inelegant, since the would all just ditto the corresponding entity class (in my personal case), were it not for the JPA annotations. Writing them off as interfaces implemented by the entity classes feels wrong as well, be it for the potential inconsistency arising when I might need to expand the model with a class that does not correspond to an entity, or for the fact that in Java the generics used to represent @OneToMany
and @ManyToMany
relationships are not (and should not be) covariant with the abstracting interfaces.
I shall now post some code to exemplify my concern:
package com.depvin.pps.orm;
import javax.persistence.*;
@Entity
@DiscriminatorValue("E")
public class EmployeeEntity extends UserEntity {
@ManyToMany
@JoinTable(name = "EmployeeProject",
joinColumns = @JoinColumn(name = "employee"),
inverseJoinColumns = @JoinColumn(name = "project"))
List<ProjectEntity> projects;
public EmployeeEntity(String username) {
super(username);
}
public List<ProjectEntity> getProjects() {
return projects;
}
}
How should the corresponding model class/interface be realized, taking into account the matters I brought up above?