Reputation: 29280
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();
}
Upvotes: 14
Views: 20791
Reputation: 5884
You need to include Animal-class in your @EntityScan in your webconfig
Upvotes: 0
Reputation: 2719
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.
Upvotes: 6
Reputation: 519
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>
Upvotes: 10
Reputation: 83081
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:
@Entity
as wellUpvotes: 2