Java/Hibernate using interfaces over the entities.

Posted by Dennetik on Stack Overflow See other posts from Stack Overflow or by Dennetik
Published on 2010-05-09T22:07:25Z Indexed on 2010/05/09 22:18 UTC
Read the original article Hit count: 225

Filed under:
|
|

I am using annoted Hibernate, and I'm wondering whether the following is possible.

I have to set up a series of interfaces representing the objects that can be persisted, and an interface for the main database class containing several operations for persisting these objects (... an API for the database).

Below that, I have to implement these interfaces, and persist them with Hibernate.

So I'll have, for example:

public interface Data {
  public String getSomeString();
  public void setSomeString(String someString);
}

@Entity
public class HbnData implements Data, Serializable {
  @Column(name = "some_string")
  private String someString;

  public String getSomeString() {
    return this.someString;
  }
  public void setSomeString(String someString) {
    this.someString = someString;
  }
}

Now, this works fine, sort of. The trouble comes when I want nested entities. The interface of what I'd want is easy enough:

public interface HasData {
  public Data getSomeData();
  public void setSomeData(Data someData);
}

But when I implement the class, I can follow the interface, as below, and get an error from Hibernate saying it doesn't know the class "Data".

@Entity
public class HbnHasData implements HasData, Serializable {
  @OneToOne(cascade = CascadeType.ALL)
  private Data someData;

  public Data getSomeData() {
    return this.someData;
  }

  public void setSomeData(Data someData) {
    this.someData = someData;
  }
}

The simple change would be to change the type from "Data" to "HbnData", but that would obviously break the interface implementation, and thus make the abstraction impossible.

Can anyone explain to me how to implement this in a way that it will work with Hibernate?

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate