One issue I'm running into is a good way to map One-To-Many relationships with JPA / Hibernate, without sacrificing SOLID principles along the way. Here's an example of this problem from a current project I'm working on:
Given the following code which defines a unidirectional One-To-Many relationship:
@Entity
@Table(name = "users")
public class User extends AggregateEntity<User> implements HasRoles, HasContactInfo, HasContacts, HasDeals {
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
@JoinColumn(name = "fk_hasContacts")
private Set<Contact> contacts;}
My understanding is that this creates an "fk_hasContacts" column in the "contacts" table, without the "Contact" class knowing or caring which object it is being referenced from. Also, notice how "User" implements the "hasContacts" interface, which creates a decoupling effect between the two entities. If tomorrow I want to add another class; say "BusinessEntity" which also has contacts, there's nothing that needs to be changed within the current code. However, after reading up on the topic in seems that this approach is inefficient from a database performance perspective.
The best way to map a @OneToMany association is to rely on the @ManyToOne side to propagate all entity state changes - As expounded upon here.
Seems to be the prevailing wisdom. Were I to engineer it that way, the "User" class would now look like this:
@Entity
@Table(name = "users")
public class User extends AggregateEntity<User> implements HasRoles, HasContactInfo, HasContacts, HasDeals {
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private Set<Contact> contacts;
And the (previously decoupled) "Contact" class would now have to look like this:
@Entity
@Table(name = "contacts")
public class Contact extends StandardEntity<Contact> {
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "fk_user")
private User user;
The key problem is that it seems from here that JPA doesn't support defining an interface as an entity attribute . So this code:
@Entity
@Table(name = "contacts")
public class Contact extends StandardEntity<Contact> {
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "fk_user")
private HasContacts hasContacts;//some class which implements the "HasUser" interface
Isn't an option. Seems one would have to chose between SOLID OOP, and valid ORM entities. After a lot of reading I still don't know whether the hit to database performance is bad enough to justify writing what amounts to tightly coupled, rigid and ultimately bad code.
Are there any workarounds / solutions to this seeming contradiction in design principles?