How do I map a Java class to a database table using JPA annotations?

To map a Java class to a database table using JPA annotations, you primarily use annotations provided by jakarta.persistence. Here is a step-by-step guide:

Key annotations for mapping:

  1. @Entity
    Marks the class as an entity that is mapped to a table.
  2. @Table (optional)
    Specifies the table name in the database. If omitted, the default table name is the class name.
  3. @Id
    Marks a field as the primary key.
  4. @GeneratedValue (optional)
    Specifies how the primary key value is generated (e.g., AUTO, SEQUENCE).
  5. @Column (optional)
    Represents a column in the table, providing options to customize the name, length, nullable flag, etc.
  6. Additional mapping annotations for relationships:
    For relationships between tables (e.g., one-to-many, many-to-one, etc.), you can use @OneToMany, @ManyToOne, @OneToOne, and @ManyToMany.

Example: Mapping a simple class

Here’s an example of a Java class mapped to a database table using JPA annotations:

package com.example;

import jakarta.persistence.*;

@Entity
@Table(name = "students") // Optional; defaults to "Student"
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // Auto-generate primary key
    private Long id;

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

    @Column(name = "email", unique = true, length = 150)
    private String email;

    @Column(name = "age", nullable = false)
    private int age;

    // Default constructor (needed by JPA)
    public Student() {
    }

    // Constructor with parameters and Getters/Setters
    public Student(String name, String email, int age) {
        this.name = name;
        this.email = email;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

Explanation of the example:

  1. @Entity
    Declares the class as an entity tied to a database table.
  2. @Table(name = "students")
    Specifies the table name as students. If omitted, the table name would default to the class name Student.
  3. @Id and @GeneratedValue
    Defines a primary key and specifies how values are generated. Here, GenerationType.IDENTITY lets the database auto-increment the key.
  4. @Column(name = "full_name", nullable = false, length = 100)
    Maps the name property to the full_name column in the table, defines the column as non-nullable, and limits its length to 100 characters.
  5. @Column(name = "email", unique = true, length = 150)
    The email column is set to be unique, ensuring no duplicate email addresses.

Save and persist the entity:

The class can now be used with JPA to persist records in the database. For instance:

Student student = new Student("John Doe", "[email protected]", 25);

EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-pu");
EntityManager em = emf.createEntityManager();

em.getTransaction().begin();
em.persist(student);  // Insert the record into the database
em.getTransaction().commit();

em.close();
emf.close();

Make sure to configure your file with your database connection details. persistence.xml


Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.4.4.Final</version>
    </dependency>
    <dependency>
        <groupId>jakarta.persistence</groupId>
        <artifactId>jakarta.persistence-api</artifactId>
        <version>3.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.