Entity

Basic Java
≈ 2 min read

An Entity is an object with persistent identity

An Entity is a Java class whose instances JPA can store in a database and restore back into objects. Such a class commonly corresponds to a table and its fields to columns, although the mapping can be customized.

@Entity
public class User {

    @Id
    private Long id;

    private String name;
}

The @Entity annotation tells the provider that the class participates in the persistence model. A field annotated with @Id defines the primary key — the value that uniquely identifies an Entity instance.

An Entity is still an ordinary Java object

An Entity can have methods, constructors, and ordinary business logic. However, JPA places several requirements on its structure: the class must be accessible to the provider, and the state that should be persisted must be described through fields or properties. An Entity also normally has a no-argument constructor with at least protected access.

protected User() {
}

public User(Long id, String name) {
    this.id = id;
    this.name = name;
}

Table and column names can be customized

@Entity
@Table(name = "users")
public class User {

    @Id
    @Column(name = "user_id")
    private Long id;
}

If the default conventions fit the project, every name does not have to be specified explicitly. Explicit mapping is useful when the database schema already exists or its names differ from the Java model.