Menu

Entities and Basic Mapping Annotations

Entities and Basic Mapping Annotations

An entity is a Java class mapped to a table. It must be annotated with @Entity, have an identifier field marked with @Id, and have a public or protected no-argument constructor.

The class should not be final, because Hibernate creates proxy subclasses for lazy loading. Without other settings, the table takes the class name, and each column takes its field name.

Common Annotations

Annotation

Purpose

@EntityMarks the class as an entity
@TableSets the table name and constraints
@IdMarks the primary key
@ColumnSets column name, length, and nullability
@TransientExcludes a field from persistence
@Entity
@Table(name = "students")
public class Student {

    @Id
    private Long id;

    @Column(name = "full_name", nullable = false, length = 100)
    private String name;

    private LocalDate dateOfBirth;

    @Transient
    private int age;

    protected Student() {}
}

Code Explanation:

  • @Table maps the class to the students table.
  • @Column maps name to full_name, disallows nulls, and limits the length to 100.
  • dateOfBirth needs no annotation. Hibernate maps java.time types directly.
  • age is derived data, so @Transient keeps it out of the table.
  • Because @Id is on a field, Hibernate reads and writes the fields directly. Placing it on a getter would switch to property access.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details