简体   繁体   English

休眠映射到一个表中的一对多

[英]Hibernate Mapping One-to-many in one table

We have the following (poorly designed?) table: 我们有以下(设计不佳?)表:

inputs:
keyword_id serial not null,
group_name string not null,
banned_term string not null

Keyword ID is the primary key. 关键字ID是主键。 there are many banned terms per group_name. 每个group_name都有许多禁止使用的术语。 The data looks like this: 数据如下所示:

keyword_id | group_name | banned_term
1 | incentivization | free money
2 | inaccuracy | we're number one
3 | incentivization | win a free ipod!

There's no join table, and group_name isn't its own entity. 没有联接表,并且group_name不是它自己的实体。 I'd like a domain object something like this: 我想要一个域对象,像这样:

class BannedTermGroup {
  Integer id;
  String group_name;
  Set<String> banned_terms;

  // ... various getters and setters
}

The only examples on this one-to-many relationship between the group name and banned terms all involve some sort of join column or join table, while group_name would always be part of some other entity. 组名和禁止术语之间的一对多关系的唯一示例都涉及某种联接列或联接表,而group_name始终是其他某些实体的一部分。 Here neither is the case. 情况并非如此。 Can this be mapped using Hibernate? 可以使用Hibernate进行映射吗?

As quoted in my previous comment, you can get the ID of the group from nowhere. 如我先前的评论中所引用,您可以从任何地方获取该组的ID。

Just to put aside this problem, you may look into Hibernate's reference, search for collections of basic types. 撇开这个问题,您可以参考Hibernate的参考,搜索基本类型的集合。 It is what you need. 这就是你所需要的。

However, you still need to have a table for the "group". 但是,您仍然需要一个用于“组”的表。

assume it is as simple as a one column table: 假设它像一列表一样简单:

KEYWORD_GROUP
--------------------
GROUP_NAME   STRING

Your original keyword table: 您的原始关键字表:

KEYWORD
--------------------
GROUP_NAME   STRING
KEYWORD      STRING

I believe this is what you need: 我相信这是您需要的:

@Entity
@Table("KEYWORD_GROUP")
public class KeywordGroup {
   [.....]

   @ElementCollection
   @CollectionTable(name="KEYWORD", joinColumns=@JoinColumn(name="GROUP_NAME"))
   @Column(name="KEYWORD")
   private List<String> keywords;
}

For the keyword_group table, you probably don't need to create a new table if you are just using this model for read. 对于keyword_group表,如果您仅使用此模型进行读取,则可能不需要创建新表。 Create a view from your original keyword table should be good enough. 从原始关键字表创建视图应该足够好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM