DEV Community

Cover image for Creating and Mapping Entities in JPA: Essential Annotations Explained
Deborah Arku
Deborah Arku

Posted on

Creating and Mapping Entities in JPA: Essential Annotations Explained

What is JPA?
JPA (Java Persistence API) is a Java standard that makes it easier to work with relational databases. Instead of writing complex SQL queries, JPA lets you map Java classes to database tables and manage data using simple Java code. In short, JPA acts as a bridge between your Java objects and database records.

Understanding Entities
Before we look further into JPA annotations, let's clarify what an entity is.

An **entity **represents a real-world object or concept that can be uniquely identified and stored in a database. If you remember your early lessons in Object-Oriented Programming (OOP), you learned that classes represent real-world objects. In JPA, we use classes to represent entities in the same way.

Here's how the mapping works:

  • *Entity *→ Java class
  • *Table *→ Physical storage of the entity in the database
  • *Column *→ Field (attribute/property) in the class
  • *Row *→ Individual instance of the entity

For example, Student can be an entity. To capture the characteristics of each student, the table will have several columns like name, gender, department, and email address. Each row in this table represents a different student.

What is Entity Mapping?
Entity mapping is the process of defining how your Java classes correspond to database tables. Using JPA annotations, we specify:

  • Which class represents a database table
  • Which field is the primary key
  • How fields map to columns
  • How entities relate to each other

These annotations tell JPA exactly how to translate between your Java objects and database records. Let's explore the most common JPA annotations.

Core JPA Annotations
@entity
This annotation declares that a class is not just an ordinary Java class, but an entity that should be mapped to a database table.

Example:

@Entity
public class Student {
    // fields, constructors, methods
}

Enter fullscreen mode Exit fullscreen mode

@id
Every database table needs a primary key. A primary key is a unique value that distinguishes one record from another. The @id annotation marks a field as the primary key of the entity.

Example:

@Entity
public class Student {
    @Id
    private Long id;
    private String name;
    private String email;
}

Enter fullscreen mode Exit fullscreen mode

@column
This annotation specifies the details of the column that a field maps to. While JPA automatically maps fields to columns with the same name, @column allows you to customize the column name, length, whether it can be null, and more.

Example:

@Entity
public class Student {
    @Id
    private Long id;

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

    @Column(name = "email_address", unique = true)
    private String email;
}
Enter fullscreen mode Exit fullscreen mode

@Table
By default, JPA uses the class name as the table name. The @Table annotation lets you customize this mapping by explicitly specifying the table name, schema, or unique constraints. This is especially useful when your class name conflicts with database reserved words or when you need to follow specific database naming conventions.

Example:

@Entity
@Table(name = "students", schema = "university_db")
public class Student {
    @Id
    private Long id;
    private String name;
}
Enter fullscreen mode Exit fullscreen mode

Relationship Annotations

In real applications, entities often have relationships with each other. JPA provides annotations to map these relationships.

@OneToOne
This annotation defines a one-to-one relationship between two entities. One instance of an entity is associated with exactly one instance of another entity.

Example: Each student has exactly one student profile.

@Entity
public class Student {
    @Id
    private Long id;
    private String name;

    @OneToOne
    @JoinColumn(name = "profile_id")
    private StudentProfile profile;
}

@Entity
public class StudentProfile {
    @Id
    private Long id;
    private String bio;
    private String photoUrl;
}

Enter fullscreen mode Exit fullscreen mode

@OneToMany
This annotation defines a one-to-many relationship. One instance of an entity is associated with multiple instances of another entity.

Example: One department has many students.

@Entity
public class Department {
    @Id
    private Long id;
    private String name;

    @OneToMany(mappedBy = "department")
    private List<Student> students;
}

@Entity
public class Student {
    @Id
    private Long id;
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
}

Enter fullscreen mode Exit fullscreen mode

@ManyToOne
This is the inverse of @OneToMany. Multiple instances of an entity are associated with one instance of another entity.

Example: Many students belong to one department (shown in the example above).

@ManyToMany
This annotation defines a many-to-many relationship where multiple instances of one entity are associated with multiple instances of another entity.

Example: Students can enroll in multiple courses, and each course can have multiple students.

@Entity
public class Student {
    @Id
    private Long id;
    private String name;

    @ManyToMany
    @JoinTable(
        name = "student_course",
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "course_id")
    )
    private List<Course> courses;
}

@Entity
public class Course {
    @Id
    private Long id;
    private String title;

    @ManyToMany(mappedBy = "courses")
    private List<Student> students;
}

Enter fullscreen mode Exit fullscreen mode

Conclusion
In this article, we explored the essentials of entity mapping in JPA, including key annotations like @entity, @id, @column, and @Table, as well as relationship annotations such as @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany. Understanding these concepts is crucial for effectively working with JPA and managing how your Java objects are stored in a relational database.

As you continue building your Java applications, these annotations will become second nature, allowing you to focus on your business logic rather than complex SQL queries.

Top comments (0)