Search code examples
javaspringjpagenerics

How to save List of objects that have a common superclass in Spring JPA inside another entity


I have a common superclass marked as @MappedSuperClass and five other classes marked as @Entity that extend the superclass. Everything works fine in saving them with a table per subclass. The problem is i have another entity that contains a List of objects belonging to the five subclasses. I need to persist that list. I tried generics but i get an error from spring. Is there a solution or do i have to keep an array of IDs instead of a list?

I tried all annotations @ManyToMany etc. I tried Generics. List<? extends SuperClass> nothing seems to work. If there is no solution what are the strategies i can apply instead of a list of IDs? P.S I'm new to spring


Solution

  • The issue you’re running into is because your common superclass is annotated with @MappedSuperclass. In JPA, a mapped superclass isn’t an entity—you can’t target it in relationships. That’s why having a List<? extends SuperClass> (or List) in your other entity doesn’t work as expected.

    Instead of using @MappedSuperclass, you should make your common superclass an actual entity and define an inheritance strategy. For example, if you want a table-per-subclass setup, you can use the JOINED strategy. Something like this:

    @Entity
    @Inheritance(strategy = InheritanceType.JOINED)
    public abstract class SuperClass {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        
        // Common fields
    }
    

    Then, each of your subclasses can simply be:

    @Entity
    public class SubClassA extends SuperClass {
        // Fields specific to SubClassA
    }
    

    And your container entity that holds the list could look like this:

    @Entity
    public class ContainerEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @OneToMany(cascade = CascadeType.ALL)
    private List<SuperClass> items;
    
    // Other fields, getters, setters
    }
    

    With this setup, JPA will recognize the polymorphic relationship. When you persist a ContainerEntity, it will handle the associated SuperClass instances (and their concrete types) properly.