开发者

What is a good solution to link different tables in Hibernate based on some field value?

I have article table and several user tables a_user, b_user, ... with exactly the same structure (but different data). I can't change anything in *_user tables except their table name prefix but can change everything else (user tables contain only user information, there is nothing about article or user_type in them).

I need to link article to a user (many-to-one), but user table name is defined by user_type field. For example

Article tab开发者_Go百科le record:
...
user_id="5"
user_type="a"

means that it is linked to a user with id=5 from a_user table (id 5 is not unique in users scope, each user table can have its id 5).

Any suggestions how to handle this situation? How can I map this relation in Hibernate (xml mapping, no annotations) so it will automatically pick up correct user for an article during select/update? How should I map user tables (one or multiple classes?)?

I would need to run some queries like this:

from Article a where a.userType=:type and a.user.name=:name

Thanks.


Hibernate has @Any annotation (and <any> xml element) for such designs.

Sorry for annotations, but I'm not good in hbm.xml. It can be translated into XML, see <any> element:

@Entity @Table(name = "Article")
public class Article {

    @Any(metaColumn = @Column(name = "user_type"))
    @AnyMetaDef(
            idType = "integer",
            metaType = "string",
            metaValues = {
                    @MetaValue(value = "A", targetEntity = UserA.class),
                    @MetaValue(value = "B", targetEntity = UserB.class)
            }
    )
    @JoinColumn(name = "user_id")
    private User user;

    ...
}

UserA and UserB shares the same schema defined by User:

@MappedSuperclass
abstract public class User {
    @Id
    private Long id;

    private String name;

    ...
}

@Entity @Table(name = "a_user")
public class UserA extends User {}

@Entity @Table(name = "b_user")
public class UserB extends User {}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜