开发者

Java DB Table inheritance?

Is it possible to do Table Inheritance in Java DB? We have a complex code model that uses inheritance and would also ben开发者_如何学运维efit from DB inheritance.

Is it possible? It doesn't seem possible from a quick google or a poke around in netbeans.

Cheers


I'm assuming that by "Java DB Table" you mean a standard SQL table, accessed via JDBC, and not a product called "Java DB Table". The answer to your question is that no, you cannot directly do inheritance in SQL. This is not a limitation of Java, JDBC or any object-relational mapping tool, but an issue with SQL itself. However, using Hibernate/JPA/JDO it's fairly easy to fake doing it, using several different methods.
So the answer to the question "Can I easily represent my really cool object iheritance hierarchy in a relational database using Java?" is, for suitable definitions of easy, Yes.


First, your question is fairly vague in the details. The more specific you are the better the community can support you. So I'm going to guess what support you are looking for and hope it helps.

If you're using something like JPA/Hibernate, you can create classes with the annotation @MappedSuperClass. When the classes are scanned, the relationship between a 'parent' table and a child table will be realized. As a quick example:

@MappedSuperClass
public class Foo {
    private Long id;
    // ... getters and setters
}

@Table("BAR")
@AttributeOverride(name="id" column=@Column(name = "BAR_ID"))
public class Bar extends Foo {
    // ... map your table
}

If you'll notice, the Foo class does not have to represent a table. It can just provide some of the common fields that span across a number of tables (typical fields like modified_by, modified_date, etc.). If Bar has an id like BAR_ID, you can then override the parent with an @AttributeOverride annotation.

While I did everything with annotations, I'm sure you can look into doing this with XML as well.


I'm not sure if I understood your question correctly .... :-(


Using an ORM solution like Hibernate (or JPA), you can have an abstract (or not) entity that has several subclasses, each mapped to a different table.

Advantages:

  • You only define once each column, and reuse it for all tables.
  • You can have some code that is generic to all these entities, if it relies on the common part.
  • Hibernate also lets you write queries that are generic
    (example : "select * from Object" returns the whole database, as it matches all your entities).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜