简体   繁体   English

为数据库中的唯一名称创建其他ID?

[英]Create additional Id for unique names in DB?

I want to create a database table that should hold lots of unique names, that may be used by other tables with reference. 我想创建一个数据库表,该表应包含许多唯一的名称,其他表可以使用该名称进行引用。

Example: 例:

table Country:
Germany
USA
France

Should I mark the String of these names as @Id , or introduce another Long id ? 我应该将这些名称的字符串标记为@Id还是引入另一个Long id

@Entity
class Country {
    //@Id private Long id;

    @Id private String name; //eg 'Germany'
}

@Entity
class Address {
    @ManyToOne
    private Country country;
}

I assume that it is better to have the names being referenced by an Id so that the names are not repeated within foreign keys in the Country table? 我认为最好用一个Id来引用名称,以免在Country表的外键中重复这些名称? Or does this not matter? 还是没关系?

Are there any advantages if a new Address is not having a String country field, but just a reference to the country (because the same country name will be reused in several addresses, thus not having dublicate name entries in the address tables). 如果新地址没有String country字段,而只是引用String country地区,是否有任何优势(因为同一国家/地区名称将在多个地址中重复使用,因此地址表中没有重复的名称条目)。

But I could imagine that a drawback might be that I do not have the Country Id before persisting a address. 但是我可以想象一个缺点可能是在保留地址之前我没有国家/地区代码。 Therefore, I'd first have to check SELECT * FROM Country WHERE name := name , check if ==null and create a new Country entry, then creating the Address . 因此,我首先必须检查SELECT * FROM Country WHERE name := name ,检查==null并创建一个新的Country条目,然后创建Address

Would you think it is better to use String or Long as Id here? 您认为在这里使用String或Long as Id更好吗?

I'd use a Long Id. 我会使用长号。

I'd avoid the string because country names aren't constant: they're known to change, and it'd suck to have to go change all the foreign key values. 我会避免使用该字符串,因为国家/地区名称不是恒定的:已知它们会更改,而且不得不更改所有外键值实在是太糟了。

I'd avoid the enum route because it'd require to you change/rebuild/recompile to handle new countries or country name changes. 我会避免使用枚举路线,因为它要求您更改/重建/重新编译以处理新的国家或国家/地区名称更改。

Another option would be to define an enum with the names of all countries and use it in your entities. 另一种选择是使用所有国家/地区的名称定义一个enum ,并在您的实体中使用它。 The values are guaranteed to be unique and it is simpler and there is no need for an additional table and superfluous joins on each query: 保证值是唯一的,并且更简单,并且每个查询都不需要额外的表和多余的联接:

public enum Country {
Germany, USA, France
}

in your entity: 在您的实体中:

@Enumerated(EnumType.STRING)
private Country country;

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

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