共享模型的hibernate映射

时间:2013-10-16 19:07:37

标签: java hibernate jpa

有3个实体类 - Item,Seller,Comment。其中,

Item 1 --- * Comment, and Seller 1 --- * Comment

如何在不添加附加表的情况下使用JPA / Hibernate注释映射类?

表结构是:

Item(id, description)
Seller(id, name)
Comment(id, entityType, entityKey, message)

其中entityType是ITEM或SELLER,entityKey是item.id或seller.id。

现在,我有以下内容:

更新:OneToMany方面现在还可以,还需要弄清楚如何让它在ManyToOne方面运行。

@Entity
@Table(name = "item_tb")
public class Item {
    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "description")
    private String description;

    *** @OneToMany
    *** @JoinColumn(name = "entityKey")
    *** @Where(clause = "entityType = 'ITEM'")
    private List<Comment> comments;
}

@Entity
@Table(name = "seller_tb")
public class Seller {
    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "name")
    private String name;

    *** @OneToMany
    *** @JoinColumn(name = "entityKey")
    *** @Where(clause = "entityType = 'SELLER'")
    private List<Comment> comments;
}

@Entity
@Table(name = "comment_tb")
public class Comment {
    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "entityType")
    private String entityType;

    @Column(name = "entityKey")
    private Integer entityKey;

    @Column(name = "message")
    private String message;

    @ManyToOne
    ...
    private Item item;

    @ManyToOne
    ...
    private Seller seller;
}

2 个答案:

答案 0 :(得分:0)

您可以在没有连接表的情况下使用One to Many双向,这意味着Comment表将具有指向item表的外键。你的关系看起来像是

Item
..............
@OneToMany(mappedBy="item")    
private List<Comment> comments;


Comment
...............
@ManyToOne
@JoinColumn(name="item_id")
private Item item;

在您的代码中,您必须正确设置关系的两面。

答案 1 :(得分:0)

我能想到两种可能性:

[1]在每个@OneToMany映射上使用Hibernate的@Where注释。这可用于将注释限制为每个集合的适当类型。

[2]使用Hibernate的继承功能(架构的每个类层次结构表)。创建两个实体SellerComment和ItemComment映射到同一个表并使用discriminimiator列(entityType)。相关类型的@OneToOmany集合:

[2]可能存在需要使用@ForceDiscriminator注释的问题。 approch在这里概述:http://www.gmarwaha.com/blog/2009/08/26/hibernate-why-should-i-force-discriminator/