将@ElementCollection映射到同一张表 [英] Map @ElementCollection to same table

查看:56
本文介绍了将@ElementCollection映射到同一张表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望Hibernate仅为我建立带有以下列的1张表:

I want Hibernate to build for me only 1 table with this columns:

id | product_id | enum_id
1    1            1 
2    1            2

即每个产品可以有许多枚举.而且我不想介绍新的链接表.

I.e. each product can have many enums. And I don't want to introduce new linking table.

所以我的问题是如何注释字段以实现这种表结构.

So my question is how to annotate my fields to achieve such table structure.

到目前为止,我有这个实体:

So far I have this entity:

@Entity
public class Entity {

   @Id
   private Long id;

   @ManyToOne( fetch = FetchType.LAZY )
   @JoinColumn( name = "product_id" )
   private Product product;     

   @ElementCollection
   @??? // what should go here? 
   private List<Enum> enums = new Arralist<>();
}

推荐答案

您建议的表中每个 Entity one 产品和 one 枚举>实例.这与您的注释无关,而是因为实体将始终为每一行生成一个新实例,因为每一行都有自己的ID.

Your proposed table will have exactly one product and one enum per Entity instance. This has nothing to do with your annotations, but with the fact that an entity will always generate a new instance for each row, because every row has its own ID.

如果删除ID列,则给定表已经是您的链接表,您只需要注释 Product 实体:

If you drop the ID column, than the given table is already your linking table and you simply need to annotate the Product entity:

@Entity
public class Product {
  // ...

  @ElementCollection
  @Enumerated
  private Set<MyEnum> enums;

}

您将需要声明 Enum 的类型,在我的示例 MyEnum 中,因为您无法绑定到任何 Enum (从数据库读取时,Hibernate不知道要实例化哪个实例.

You will need to declare the type of the Enum, in my example MyEnum, as you can't bind to any Enum (Hibernate wouldn't know which one to instantiate when reading from the database).

如果要保留任何现有的表或列名称,则可以使用其他 @CollectionTable .但是我建议使用默认值,因为它使代码更易于阅读.

If you want to stick to any existing table or column names you can use the additional @CollectionTable. But I would propose to use the defaults, as it makes the code easier to read.

如果真的像第一次尝试那样,需要一个枚举列表(该列表允许重复并存储项目的排序),则您需要为列表中的索引增加一列.您可以使用以下方法实现此目标:

And if you really, as in your first attempt, need a list of enums (which allows duplicates and stores the ordering of items), than you need an additional column for the index in the list. You can achieve this with:

@ElementCollection
@Enumerated
@OrderColumn
private List<MyEnum> enums;

这篇关于将@ElementCollection映射到同一张表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆