Skip to content
This repository has been archived by the owner on Jun 16, 2022. It is now read-only.

DB Entity Best Practices

Joshua Zenn edited this page Feb 26, 2022 · 1 revision

Primary Key Field

Every entity should have a primary key field with the following annotations/attributes:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, updatable = false)
private Long id;

The @Id annotation marks the entity member as the primary key of the associated table, and as the field to use when binding to other entity classes.

The @GeneratedValue attribute denotes that the AUTO generation type should be used when selecting unique primary keys. We need to use the automatic selection method here because we use two different databases with different sequencing types. When we are using the H2 database when running JUnit tests locally, we need the web application itself to keep track of what primary key values have not been used. This is fine because the database will be wiped at the end of every test, so we do not care about the fact that this primary key sequencing data is lost on application reboot. On the other hand, when we are using Postgres in development and in production, Postgres has a special SQL object type called SEQUENCE that can keep track of what primary keys have not been used. This method of sequence generation is extremely fast, works when we have multiple instances of our server running, and can survive application restarts.

@Column adds some additional attributes to the underlying SQL column. Here we are specifying that the ID can never be updated (for security and performance reasons this should never be allowed).

Finally we have the actual entity member declaration. Choose a name that accurately represents the field (usually id unless you are doing something odd). This field should also be a Long as this gives us 64 bits worth of data instead of the normal 32 bits from the Integer data type. Yes, it does make more sense here, but do not use the unsigned Long data type. Some of the underlying database drivers have issues converting that value type.