Spring Data JPA : Creating an abstract repository
Solution 1
I had similiar error. I solved it by adding mapping of my entity class to my persistence.xml file.
So maybe add something like this to your persistence.xml:
<persistence-unit>
...
<class>yourpackage.Animal</class>
...
</persistence-unit>
Solution 2
I was having this exact problem, and I found the solution: You need to either use @MappedSuperclass
OR @Inheritance
, not both together. Annotate your Animal
class like this:
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {}
The underlying database scheme will remain the same, and now your generic AnimalRepository
should work. The persistence provider will do the introspection and find out which table to use for an actual subtype.
Solution 3
I guess you're running Hibernate as your persistence provider, right? I've stumbled over problems with this scenario with Hibernate as the type lookup against the Hibernate metamodel doesn't behave correctly contradicting what's specified in the JPA (see this bug for details). So it seems you have two options here:
- Change the abstract superclass to be an
@Entity
as well - Switch to a different persistent provider
Related videos on Youtube
Marty Pitt
Updated on June 04, 2022Comments
-
Marty Pitt almost 2 years
Given the following classes:
@MappedSuperclass @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) @DiscriminatorColumn(name="animalType",discriminatorType=DiscriminatorType.STRING) @QueryExclude public abstract class Animal {} @Entity @DiscriminatorValue("dog") public class Dog {} @Entity @DiscriminatorValue("cat") public class Cat {}
Is it possible somehow to configure a JPA Repository for
Animal
?I've tried
public interface AnimalRepository extends JpaRepository<Animal,Long>
However this fails with:
java.lang.IllegalArgumentException: Not an managed type: Animal
Is there a way to configure this?
I'd like to be able to perform tasks like:
@Autowired private AnimalRepository repository; public void doSomething() { Animal animal = repository.findById(123); animal.speak(); }
-
Marcel Stör over 11 yearsThe only sensible answer so far. The JPA annotations are just wrong. Additionally to what you said, why would you need a discriminator column if there's a table per class? Makes no sense.
-
raksja almost 11 years+1 Helped me in resolving the issue similar to the one posted.. thanks for the reminder..