通过单个列将多个实体映射到Hibernate中的单个实体

时间:2019-03-05 01:07:20

标签: java hibernate spring-data-jpa hibernate-mapping

我有一个可以附加到用户,文章,企业,产品和其他实体的媒体项目。

我发现处理此问题的最佳方法是,有一个作为外键的“ object_id”和一个将保存对象类型(产品,用户,商品等)的“ object_type”。

这是创建媒体实体的最佳方法吗?

@Entity
@Table(name = "media")
public class Media implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Size(max = 25)
    @Column(name = "filename", nullable = true, unique = false)
    private String filename;

    @Size(max = 12)
    @Column(name = "object_type", nullable = true, unique = false)
    private String objectType;

    @Column(name = "object_id", nullable = true, unique = false)
    private Long objectId;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @Where(clause = "object_type = business")
    @JoinColumn(name = "object_id", referencedColumnName = "id", updatable = false, insertable = false)
    private Business business;

    ... ... ... //briefed
}

0 个答案:

没有答案