FRANCISCO BERNAD
FRANCISCO BERNAD

Reputation: 533

Hibernate/JPA Inheritance class change

Hi I have a Spring project and Im migrating everything from my handmade persistent layer using sql to Hibernate/JPA ORM.

I facing the following situation: I have an AbstractUser class, a SimpleUser and a ProviderUser. Simple and Provider extend form AbstractUser. What differentiates Provider from SimpleUser is that the first one has extra fields and entities the second one does not have. Im using @Inheritance(strategy = InheritanceType.SINGLE_TABLE) to map my inheritance and everything is running smoothly.

The thing is I dont know how to manage the action of upgrading a SimpleUser to a Provider. Two things come to my mind:

  1. Removing the entity form the database and creating a new one using the Provider implementation.
  2. Changing the DiscriminatorColumn value for the SimpleUser to the one that refers to Provider.

I really think neither of these ways are correct, but they work. What is the best way of doing this?

Upvotes: 1

Views: 309

Answers (1)

Changing the type of an existing object is not a meaningful concept in Java: Object just are something. JPA, however, is essentially a very complicated magic view over a relational (usually) database, and it's entirely possible to have multiple classes referring to the same table; I've done this before with a read-only @Entity FooSummaryView that only retrieves a few columns out of some large legacy monstrosity.

In general, my recommendation would have been to have your ProviderCharacteristics live in a separate table with @MapsId using the User FK as the PK, but if you don't want to migrate your actual database schema, then you'll need to manually manipulate your row to make the change. Your second option of simply modifying the discriminator in JDBC (along with whatever updates are required to satisfy validation constraints) seems the least invasive.

Upvotes: 1

Related Questions