开发者

How do I extend a hibernate annotated class to point a field to a different hibernate entity?

Let's say I have the following class structure:

/** Boring bits snipped */
@Entity
@Table(name = "Foo")
public class Foo {
    @JoinColumn(name = "id")
    private Bar bar;
    /** Other flat data goes here */
}

@Entity
@Table(name = "Bar")
public class Bar {
    /** Some data goes here */
}

For reasons I'm not going to go into, I have copies of these tables which I want to also map too, which should appear in Java开发者_开发技巧 to also be Foo and Bar objects. Most importantly, the relationships between tables should be between the copied tables when dealing with copied objects.

What is the most correct way of doing this?

I'm guessing I can probably do something like this:

@Entity
@Table(name = "OtherFoo")
public class OtherFoo extends Foo {
    @JoinColumn(name = "id")
    private OtherBar bar;
}

@Entity
@Table(name = "OtherBar")
public class OtherBar extends Bar {
}

But is that the right way to do it?


You're close, but you can't just inherit from another entity and change the table like that. Entity inheritance has to follow one of the provided inheritance models. It may be for your use case as simple as adding @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) to the superclass. There are some limitations to this if you have some more complicated mappings with other classes. Since it won't be able to tell which table a superclass based mapping is actually in, it can't join through it. And mappings to the superclass will require checking both tables every time. You also of course need unique ID generation across all the tables in the hierarchy. You may want to consider using an abstract superclass and having both concrete entities be leaf classes. Then at least you can always work with just a single table when you know which one it is.

Alternately you can declare your column mappings in an @MappedSuperclass and each subclass can then be an entity with a table mapping. That might work better if it's legacy data and you don't have unique IDs across the 'regular' and 'copy' tables.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜