balteo
balteo

Reputation: 24679

Spring Data o.s.data.jpa.repository.JpaRepository's save method and polymorphism

I have the following method call in my service layer:

saveAdvertisement(childminderAdvertisement);

..which in calls the following method from AdvertisementServiceImpl:

public void saveAdvertisement(Advertisement advertisement) {
  advertisementRepository.save(advertisement);
}

AdvertisementRepository is a org.springframework.data.jpa.repository.JpaRepository parameterized as follows:

 JpaRepository<Advertisement, Long>;

Here are my entities:

Advertisement:

@RooJavaBean
@RooToString
@RooEquals
@RooJpaEntity(inheritanceType = "TABLE_PER_CLASS")
@Entity
public abstract class Advertisement {
...

ChildminderAdvertisement:

@RooJavaBean
@RooToString
@RooEquals
@RooJpaEntity
@Entity
public class ChildminderAdvertisement extends Advertisement {
...

I noticed that the AdvertisementRepository (which is type-parametized with the super class Advertisement) manages to persist instances of ChildminderAdvertisement properly.

My question is twofold:

- how does Spring Data Jpa manages to persist an instance of the subclass whereas the I use the JpaRepository of the super class?

- What are the disadvantages (if any) of using the super class as the type parameter?

Upvotes: 0

Views: 1230

Answers (1)

V G
V G

Reputation: 19002

To Q1: it is not Spring that manages to persist the instance of subclass, but it is your JPA provider. Spring only delegates the call to the JPA provider. And that in turn manages that by calling instance.getClass() inspecting if that class is an persistable class (i.e a @Entity).

To Q2: I personally don't see any disadvantages. OF course, if you need an extension of JpaRepository that works ONLY with the more specific ChildminderAdvertisement subtype (e.g only on save of a ChildminderAdvertisement you have to log some extra stuff), then you need an implementation of the JpaRepository<ChildminderAdvertisement, Long>.

Upvotes: 1

Related Questions