views:

45

answers:

1

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

+3  A: 

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 {}
axtavt
Thanks, looks like it is exactly what I need.
serg