Entity Mapping

Basic Spring
≈ 2 min read

How a Java class is connected to a table

Spring Data JDBC can build mappings by convention: a class corresponds to a table, and its properties correspond to columns. If names differ between Java and the database, the connection can be specified explicitly with annotations. The main special part of the model is the entity identifier marked with @Id.

@Table("customers")
class Customer {
    @Id
    Long id;

    @Column("full_name")
    String name;

    boolean active;
}

Here the Customer object is connected to the customers table, the name field is connected to the full_name column, and active can be mapped by naming convention.

Mapping is part of the schema contract

Annotations do not magically create a suitable data structure for every class. Column types, constraints, keys, and the database schema itself must match the application model. When a name or structure changes, it is important to treat the Java class and SQL schema as two sides of the same contract.

Do not add an annotation just for explicitness. If Spring Data JDBC conventions already connect a property to the correct column unambiguously, extra mapping often only adds noise to the model.