Elias Garcia
Elias Garcia

Reputation: 7282

Handle different user types with Hibernate

I'm starting a web app project with Spring framework + Hibernate. I want to model two different types of users in the application: doctors and patients. They have some common attributes like name, email, telephone number etc, but the doctors have more specific attributes like collegiate number, specialities, studies etc.

This is an E-R model (Hibernate approach) simplified without attributes.

enter image description here

As you can see, the relationships will become 1 to 1, but one of them will always be null. I've also though about using inheritance but I've never worked with it in Hibernate so I don't know which is the best approach and why. Which is the simplest and efficient way to go here?

Thanks!

Upvotes: 2

Views: 808

Answers (1)

Naros
Naros

Reputation: 21123

The @Inheritance approach is just one way to share common attributes between two managed types in a persistence context. Don't forget that @MappedSuperclass does precisely the same without coupling the two data types together in any hierarchical sense.

One thing to consider is whether a Doctor can be a Patient from a domain perspective, and if so, what implications does that open up from an API perspective?

Would it be acceptable to call #getPatientDiagnosis(Patient patient) and pass it a Doctor? From a code perspective, it compiles and is logical because you elected inheritance, but from a domain perspective, that makes no sense.

This is one reason I often advocate for a separation in domain vs persistence models. There is often design decisions that make perfect sense from a data model perspective at the data store, but those decisions introduce technical debt at higher abstractions.

If it were me reusing my entities as my domain models, I'd elect @MappedSuperclass unless you have another compelling reason to use inheritance in this case.

Upvotes: 1

Related Questions