Interfaces with hibernate annotations

molleman picture molleman · Apr 6, 2010 · Viewed 24.3k times · Source

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

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

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "folder_id", updatable = false, nullable = false)
   private int fId;

   @Column(name = "folder_name")
   private String folderName;

   @OneToMany(cascade = CascadeType.ALL)
   @JoinTable(name = "FOLDER_JOIN_FILE_INFORMATION_TABLE", joinColumns = 
{ @JoinColumn(name = "folder_id") }, inverseJoinColumns = 
{ @JoinColumn(name = "file_information_id") })
    private List< Hierarchy > fileInformation = new ArrayList< Hierarchy >();
}

above and below are 2 classes that implement an interface called Hierarchy, the folder class has a list of Hierarchyies being a folder or a fileinformation class

@Entity
@Table(name = "FILE_INFORMATION_TABLE")
public class FileInformation implements Serializable, Hierarchy {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "file_information_id", updatable = false, nullable = false)
  private int ieId;
  @Column (name = "location")
  private String location;
}

I have searched the web for someway to annotate or a workaround but I cannot map the interface which is simply this

public interface Hierarchy {

}

I get a mapping exception on the List of hierarchies with a folder but I don't know how to map the class correctly.

Answer

P&#233;ter T&#246;r&#246;k picture Péter Török · Apr 6, 2010

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:

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)...