To create a basic Hibernate entity using annotations, follow these steps:
1. Add Required Dependencies
Ensure you have added the required dependencies for Hibernate, JPA (jakarta.persistence
), and any database (e.g., H2 for testing) in your pom.xml
. For example:
<dependencies>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.4.Final</version>
</dependency>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.224</version>
<scope>runtime</scope>
</dependency>
<!-- JPA API -->
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
2. Create an Entity Class
An entity class represents a table in the database and should be annotated with @Entity
. For example:
package org.kodejava.hibernate;
import jakarta.persistence.*;
@Entity
@Table(name = "students") // Maps to a table named 'students'
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // Auto-incremented primary key
private Long id;
@Column(name = "name", nullable = false) // Maps field to a column
private String name;
// Default constructor
public Student() {}
// Constructor with arguments
public Student(String name) {
this.name = name;
}
// Getters and setters
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;
}
}
Explanation of Annotations
@Entity
: Marks the class as an entity that maps to a database table.@Table(name = "table_name")
: Specifies the name of the database table (optional). If omitted, the table will use the class name.@Id
: Marks the field as the primary key.@GeneratedValue(strategy = GenerationType.IDENTITY)
: Specifies auto-generation of primary key values.@Column(name = "column_name")
: Maps a class field to a specific table column (optional). Omitting this will map the field name to a column with the same name.
3. Specify Entity in Hibernate Configuration
Ensure this entity is configured in your hibernate.cfg.xml
file, or programmatically added when building the SessionFactory
. In the XML file, include:
<mapping class="org.kodejava.hibernate.Student" />
4. Persist Data Using Hibernate
You can now use Hibernate to perform CRUD operations on this entity. For example, to save a Student
:
package org.kodejava.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateApp {
public static void main(String[] args) {
// Create a SessionFactory and configure Hibernate
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml") // Load the configuration file
.addAnnotatedClass(Student.class) // Add annotated class
.buildSessionFactory();
// Open session
try (Session session = factory.openSession()) {
// Create a new student entity
Student student = new Student("John Doe");
// Start a transaction
session.beginTransaction();
// Save the student to the database
session.persist(student);
// Commit the transaction
session.getTransaction().commit();
System.out.println("Student saved successfully with ID: " + student.getId());
} finally {
factory.close(); // Close the factory
}
}
}
Summary
By using annotations like @Entity
, @Table
, @Id
, and @Column
, you can define the structure of your database table directly within the Java entity class. Hibernate simplifies interacting with the database and reduces the amount of boilerplate code involved.