Right now we have a JPA entity defined as:
@Entity
@Table(name="Foo")
public class Foo extends ParentClass {
...
}
Imagine that some Foo objects have been persisted in the database already. What would be the best way to programmatically change those persisted records to a sibling subclass of type Bar?
@Entity
@Table(name="Bar")
public class Bar extends ParentClass {
...
}
We do not want to change the database schema, just the entity type of the already persisted Foo objects. I am hoping there is a better method than the only one I have thought of, which is manually grabbing the Foo objects, remapping to Bar, and re-persisting.
Particularly I prefer to do it using pure SQL migration. In my company we use liquibase to version our database schema. So, to do the migration we just create changelogs for it.
Some argue that it’s not the best solution, but I find it simple and quite powerful. In my opnion, for big projects it’s the way to go.
EDIT:
Now that I see that you can’t change the schema. I don’t think this is possible in an easy way programmatically. You would need somekind of “TransformerService” between Foo and Bar, that simply copies the common parent fields, deletes the old
Fooand persist the newBar.What I would do is to break the hierarchy and componentize
ParentClass, so you can transfer only it betweenFooandBar, viceversa. This way you won’t need to copy the fields or anything like that. It may need a lot of refactoring, but componentizing is better than creating big/complex hierarchies.Or you can just run an SQL that changes the object directly at database. It’s ugly, but it’s the only way I see you could do something like that.