Spring Data JPA : Creating an abstract repository

19,079

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:

  1. Change the abstract superclass to be an @Entity as well
  2. Switch to a different persistent provider
Share:
19,079

Related videos on Youtube

Marty Pitt
Author by

Marty Pitt

Updated on June 04, 2022

Comments

  • Marty Pitt
    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
    Marcel Stör over 11 years
    The 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
    raksja almost 11 years
    +1 Helped me in resolving the issue similar to the one posted.. thanks for the reminder..