Orest
Orest

Reputation: 6748

Hibernate upgrade object from parent class to child class in JOINED inheritance

I'm using Spring Data Jpa and Hibernate on my project.

I have three tables:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
class Parent {
   String id;
   String name;
}

@Entity
class FirstChild extends Parent {
   ...
}

@Entity
class SecondChild extends Parent {
   ...
}

On the first step of my logic I should save Parent object without child type. And on the second step I know to which Child table it should belong.

For example:

Parent parent = parentRepository.findById("id");

FirstChild firstChild = new FirstChild();
firstChild.setId(parent.getId());
firstChild.setName(parent.getName());

parentRepository.save(firstChild);

But when I do a Hibernate save it throws me exception:

o.h.e.i.DefaultLoadEventListener Load request found matching entity in context, but the matched entity was of an inconsistent return type; returning null

As I understand it doesn't know how to upgrade entity from parent to child type and just throws an exception because of conflict - entity with same id is already there.

Is there any solutions for this problem?

Upvotes: 3

Views: 2066

Answers (1)

crizzis
crizzis

Reputation: 10716

JPA is a means of mapping your Java domain model onto a relational database schema. Since there is no such thing as 'promoting a parent class to a child class' in Java, there is no support in JPA for such an operation.

That being said, you could probably achieve the desired behavior using a native update query. You would need to update the discriminator column (DTYPE) column, and insert a new row into the table corresponding to the child entity (note that in the SINGLE_TABLE strategy, updating the discriminator column would suffice).

A much better solution IMHO, is to delete the parent entity and insert a new child entity. If you're concerned about referential integrity, perhaps you should switch from inheritance to composition.

Upvotes: 2

Related Questions