简体   繁体   中英

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 ?

@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? 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).

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 .

Would you think it is better to use String or Long as Id here?

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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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