I have to map a legacy database with tables that have a lot of fields and relations. For example (simplified code),
@Entity @Table(name = "VISIT") public class VisitEntity { @Id private Integer Id; @ManyToOne @JoinColumn(name = "CD_COMPANY") private CompanyEntity company; @ManyToOne @JoinColumn(name = "CD_EMPLOYEE") private EmployeeEntity employee; @ManyToOne @JoinColumn(name = "CD_VISIT_TYPE") private VisitTypeEntity visitType; // A lot more fields and relations }
All other entityes used in the VisitEntity also have a lot of fields and more relations. For example, the EmployeeEntity is mapped as follows:
@Entity @Table(name = "EMPLOYEE") public class EmployeeEntity { @Id private Integer Id; @Column(name = "EMP_NAME") private String empName; @ManyToOne @JoinColumn(name = "CD_DEPARTMENT") private DepartmentEntity department; @ManyToOne @JoinColumn(name = "CD_CITY") private CityEntity city; @ManyToOne @JoinColumn(name = "CD_CATEGORY") private CategoryEntity category; // A lot more fields and relations }
With this classes, a simple find() in the VisitEntity will generate a query with more than 400 columns and more than 40 joins. I’m affraid that, in the future, this will represent a performance problem. I see two ways of reducing this number (assuming that when I use a VisitEntity I only need the field Id and name from the EmployeeEntity:
- Insted of using the find method of the entityManager use a TypedQuery referencing only a subset of the filed of the relation tables. For example:
SELECT v, e.id, e.empName, <more subsets from other tables> FROM VisitEntity v LEFT JOIN EmplooyEEEntity e WHERE v.id = :id
Even using query with a smaller list of fields, I think the JPA will have to create all the main entities.
- Use auxiliary entities. For example instead of unsing an EmployeeEntity I’ll create a VisitEmployeeEntity with the fields Id and Name only. This way, the find() method will query only the 2 fields of the EMPLOYEE table.
I appreciate more the second approach, even if it represent that I have to create more small classes.
Since I’m also new to the ORM world, what is your experience/opinon in this matter?