对一些@OneToOne映射使用通用数据对象(和表)

时间:2015-05-06 09:03:55

标签: java hibernate

我希望有一个映射到单个数据库表的“通用”对象,而不是将几个小对象(它们大多数具有相同的属性,如ID和NAME)映射为@OneToOne,在这种情况下,应该用一种鉴别器列group_id来引用。

代码示例应该清楚我想要实现的目标:

@Entity
@Table(name = "GENERAL_DATA")
public class GeneralData {

    @Id
    @Column(name = "GROUP_ID")
    private int groupId;

    @Id
    @Column(name = "ID")
    private int id;

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

@Entity
@Table(name = "INVOICE")
public class Invoice {

    @OneToOne
    @JoinColumn(name = "STATUS")
    private GeneralData status;

    @OneToOne
    @JoinColumn(name = "COLOR")
    private GeneralData color;
}

GeneralData的数据库表结构应如下所示:

group_id    id     name
-----------------------------
1           1      Active 
1           2      Processing 
1           3      Cancelled
2           1      Blue 
2           2      Green 
2           3      Red 

1 个答案:

答案 0 :(得分:0)

为什么不摆脱GeneralData实体并在发票实体中使用简单的枚举?如果您指定了状态/颜色,则更好。

@Entity
@Table(name = "INVOICE")
public class Invoice {

    @Column(name = "STATUS")
    private Status         status;

    @Column(name = "COLOR")
    private Color         color;

}

public enum Status {
    ACTIVE,
    PROCESSING,
    CANCELLED
}

// ...