16

Given the following class structure:

@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal  {}

@Entity
public class Dog {}

@Entity
public class Cat {}

With Spring Data JPA, is it possible to use a generic Animal Repository to persist an Animal at runtime without knowing which kind of Animal it is?

I know I can do it using a Repository-per-entity and by using instanceof like this:

if (thisAnimal instanceof Dog) 
    dogRepository.save(thisAnimal);
else if (thisAnimal instanceof Cat)
    catRepository.save(thisAnimal);
} 

but I don't want to resort to the bad practice of using instanceof.

I've tried using a generic Repository like this:

public interface AnimalRepository extends JpaRepository<Animal, Long> {}

But this results in this Exception: Not an managed type: class Animal. I'm guessing because Animal is not an Entity, it's a MappedSuperclass.

What's the best solution?

BTW - Animal is listed with the rest off my classes in persistence.xml, so that's not the problem.

CFL_Jeff
  • 2,589
  • 3
  • 31
  • 49

1 Answers1

9

Actually the problem is with your mapping. You either use @MappedSuperclass or @Inheritance. Both together don't make sense. Change your entity to:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal  {}

Don't worry, the underlying database scheme is the same. Now one, general AnimalRepository will work. Hibernate will do the introspection and find out which table to use for an actual subtype.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Should `Animal` be listed as a class in my persistence unit in `persistence.xml`? Your suggested changed is causing a new exception: `Unable to build EntityManagerFactory`. – CFL_Jeff Jan 11 '13 at 21:35
  • @CFL_Jeff: typically I rely only on annotations, so I'm not sure. Can you publish full stack trace somewhere, including `Caused by`? – Tomasz Nurkiewicz Jan 11 '13 at 21:38
  • It seems as though I have other problems in addition to this one. I believe you have helped me solve the issue at hand, and I will work on the new problems. Thanks! – CFL_Jeff Jan 11 '13 at 21:48
  • 1
    @CFL_Jeff: please post link to follow-up questions if you have any. – Tomasz Nurkiewicz Jan 11 '13 at 21:54