Persist collection of interface using Hibernate

前端 未结 3 1874
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 05:44

I want to persist my litte zoo with Hibernate:

@Entity
@Table(name = \"zoo\") 
public class Zoo {
    @OneToMany
    private Set animals = new          


        
相关标签:
3条回答
  • 2020-12-01 05:48

    I think you have to annotate the interface too with @Entity and we have to annotate @Transient on all getters and setters of interface.

    0 讨论(0)
  • 2020-12-01 05:54

    I can guess that what you want is mapping of inheritance tree. @Inheritance annotation is the way to go. I don't know if it will work with interfaces, but it will definitely work with abstract classes.

    0 讨论(0)
  • 2020-12-01 06:11

    JPA annotations are not supported on interfaces. From Java Persistence with Hibernate (p.210):

    Note that the JPA specification doesn’t support any mapping annotation on an interface! This will be resolved in a future version of the specification; when you read this book, it will probably be possible with Hibernate Annotations.

    A possible solution would be to use an abstract Entity with a TABLE_PER_CLASS inheritance strategy (because you can't use a mapped superclass - which is not an entity - in associations). Something like this:

    @Entity
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public abstract class AbstractAnimal {
        @Id @GeneratedValue(strategy = GenerationType.TABLE)
        private Long id;
        ...
    }
    
    @Entity
    public class Lion extends AbstractAnimal implements Animal {
        ...
    }
    
    @Entity
    public class Tiger extends AbstractAnimal implements Animal {
        ...
    }
    
    @Entity
    public class Zoo {
        @Id @GeneratedValue
        private Long id;
    
        @OneToMany(targetEntity = AbstractAnimal.class)
        private Set<Animal> animals = new HashSet<Animal>();
    
        ...
    }
    

    But there is not much advantages in keeping the interface IMO (and actually, I think persistent classes should be concrete).

    References

    • Annotations, inheritance and interfaces
    • using MappedSuperclass in relation one to many
    • Polymorphic association to a MappedSuperclass throws exception
    0 讨论(0)
提交回复
热议问题