Interfaces with hibernate annotations

后端 未结 2 1827
感情败类
感情败类 2021-01-13 01:32

i am wondering how i would be able to annotate an interface

@Entity
@Table(name = \"FOLDER_TABLE\")
public class Folder implements Serializable, Hierarchy {
         


        
相关标签:
2条回答
  • 2021-01-13 01:42

    You can map interfaces in Hibernate, as part of inheritance hierarchies. This is quite surely possible with XML mapping, as it is described in Chapter 9 of the Hibernate reference, among others.

    Annotation based mapping is a different story though. I am not so familiar with it, but Java Persistence with Hibernate includes examples for this too. Adapted to your case, it would look like

    @MappedSuperclass
    public interface Hierarchy {
    }
    
    @Entity
    @Table(name = "FOLDER_TABLE")
    public class Folder implements Serializable, Hierarchy { ... }
    
    @Entity
    @Table(name = "FILE_INFORMATION_TABLE")
    public class FileInformation implements Serializable, Hierarchy { ... }
    

    This mapping would use a table per concrete class with implicit polymorphism.

    However, other sources suggest that annotation support for interfaces may not be working / stable yet:

    • there is a related open bug report on using the @Entity annotation with interfaces, which also includes some patches,
    • here is a related (fairly old) thread, describing a workaround using XML mapping.

    So you may need to experiment, including changing your inheritance mapping strategy, maybe turning the interface into an abstract class (if it's possible - since a class can only extend a single base class)...

    0 讨论(0)
  • 2021-01-13 01:58

    A little Googling turned up...

    You can use interfaces internally but you can't map interfaces in hibernate, you have to map classes, regardless of whether you are using xml mapping or annotation mapping. hibernate is handling lifecycle of your persistent objects so it needs to know what class to instantiate so you need to provide this information to it... I am not even sure how what you suggesting would even look like? how would you provide implementation for given interface to hibernate at runtime to instantiate?

    http://forum.springsource.org/showthread.php?t=67420

    So it looks like you are out of luck.

    0 讨论(0)
提交回复
热议问题