Hibernate polymorphism

后端 未结 2 1647
醉梦人生
醉梦人生 2021-02-04 08:47

This is a Hibnerate polymorphism question and a data model design question; they are intertwingled. I\'ve used Hibernate in the past, and have enjoyed it, but sometimes I find

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 09:03

    This is absolutely possible. You could associate the notes with the abstract Fruit class instead of repeating them in each of the implementations:

    @Entity
    @Inheritance
    public abstract class Fruit {
       private Set notes;
       ...
    
       @OneToMany(cascade = CascadeType.ALL, mappedBy = "fruit")
       public Set getNotes() {
           return notes;
       }
    }
    
    @Entity
    public class Apple extends Fruit {
       ...
    }
    
    
    @Entity
    public class Orange extends Fruit {
       ...
    }
    
    @Entity
    public class Note {
       private String theNote;
    
       @ManyToOne
       private Fruit fruit;
       ...
    }
    

    Ét voilà!

    -- Addition based on comment: JPA provides multiple strategies for dealing with inheritance. The relevant section in the Java EE tutorial should help you get started.

    Basically, your options are:

    • Storing everything in one table and using a discriminator column to know which row is which type
    • Storing each concrete class (Apple and Orange) in a separate table
    • Having a common Fruit table with a discriminator column, and Apple and Orange tables with a foreign key to the Fruit table

    Another edit: Noticed this is a Hibernate, not a JPA question. Does not make too much of a difference, though, as the options are the same. Here's the relevant section in the Hibernate docs.

提交回复
热议问题