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:
@Entity
Marks the class as an entity that is mapped to a table.@Table
(optional)
Specifies the table name in the database. If omitted, the default table name is the class name.@Id
Marks a field as the primary key.@GeneratedValue
(optional)
Specifies how the primary key value is generated (e.g., AUTO, SEQUENCE).@Column
(optional)
Represents a column in the table, providing options to customize the name, length, nullable flag, etc.- 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:
@Entity
Declares the class as an entity tied to a database table.@Table(name = "students")
Specifies the table name asstudents
. If omitted, the table name would default to the class nameStudent
.@Id
and@GeneratedValue
Defines a primary key and specifies how values are generated. Here,GenerationType.IDENTITY
lets the database auto-increment the key.@Column(name = "full_name", nullable = false, length = 100)
Maps thename
property to thefull_name
column in the table, defines the column as non-nullable, and limits its length to 100 characters.@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>