简体   繁体   中英

JPA OneToOne relationship to two different types

I'm using Hibernate JPA implementation to map a relational database to my model objects.

Please see the simplified diagram:

在此处输入图片说明

In my application, I need one customer to have one implant or one prosthesis at a time, not both is possible. I would like to have only one field in my Customer model to link the Prosthesis or the Implant, that would be great, but I didn't figured out how..

For now, I'm thinking of not using any relation mapping, and setting Customer fields like:

  • field "type" : Implant or Prosthesis
  • field "prosthesis" : nullable
  • field "implant": nullable

And performing, based on type's value, a JPQL query to get a DTO (syntax new my.package.dto.Prosthesis(...) from Prosthesis if the type is Prosthesis, and so on for Implant).

Except if you prove I'm wrong, I'm afraid a relation mapping could try a join between Customer table and Prosthesis table even if the Customer's type is Implant for example. I would like to avoid that unnecessary query.

Any optimisation proposition among SO community ?

Thanks a lot

If your table implant and prosthesis are not simplified you could merge them, if you don't mind having a null value. So that in your customer table you have only one field linking to either prosthesis or implant ensuring having only one type at a time. Then your genericWordAboutImplantAndProsthesis table would look like :

  • genericWordAboutImplantAndProsthesisId
  • brand
  • model
  • productionDate
  • powered(null)
  • location(null)

You can add a field type as you mentioned or deduce it depending on which field (powered or location) isn't null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM