开发者

Hibernate: How to mapping different selector in R(selector,key, *) to different fields?

Please let me just show the code,

@Entity
class R {
    @Id
    Long id;

    String selector;

    long fkey;

    // other columns...
}

@Entity
class Foo {

    @Id
    Long id;

    // selec开发者_如何学Got * from R where selector='A' and fkey=Foo_id
    @OneToMany
    Set<R> aSet;

    // select * from R where selector='B' and fkey=Foo_id
    @OneToMany
    Set<R> bSet;
}

Here, I can't split R into two tables: R_A and R_B because the selector is variant.

I know I can create view R_A and R_B, but I don't know how to let Hibernate generate DDL for views. Or maybe I should specify custom SQL query in entity annotations? Like,

@Entity
@SourceSQL("select * from R where selector='A')
class R_A { ... }

or maybe something like this,

@Entity
class Foo {

    @Id
    Long id;

    @OneToMany
    @RestrictJoin("selector = 'A'")
    Set<R> aSet;

    @OneToMany
    @RestrictJoin("selector = 'B'")
    Set<R> bSet;
}

Well, Thanks in advance.


One option is the @Filter annotation, take a look at: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-hibspec-filters. Here's a nice example on how to use them: http://java.dzone.com/articles/introduction-hibernate-filters.

The filter doesn't need to have a parameter, check out this other example: https://forum.hibernate.org/viewtopic.php?f=1&t=996694&start=0.

Note that you need to enable the filter for each session, you could use a filter to do it: http://forum.springsource.org/showthread.php?t=61464.

If you decide to go the one class per selector, you might want to consider inheritance and the @DiscriminatorColumn annotation, like: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#d0e1168


If you want to store a collection of stuff from another table, maybe something along the lines of this could be useful?

@org.hibernate.annotations.CollectionOfElements
@JoinTable (name = "R_A", joinColumns = @JoinColumn(name="ra_id", referencedColumnName="id"))
@org.hibernate.annotations.MapKey (columns = @Column(table = "R_A", name = "key_content"))
@Column(table = "R_A", name = "value_content")
private Map<String, String> raData = new HashMap<String, String>();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜