HB CRUD

Hibernate makes it easy to perform CRUD operations using Session and Transaction. In this section, we'll cover:

  • Create (Insert Data)
  • Read (Retrieve Data)
  • Update (Modify Data)
  • Delete (Remove Data)



Entity Class with Mappings:

Student.java
import jakarta.persistence.*;

@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

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

@Column(unique = true)
private String email;

// Constructors
public Student() {}
public Student(String name, String email) {
this.name = name;
this.email = email;
}

// 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; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}

Create (Insert Data):

To insert a new record into the database, we use the persist() method.

Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Main {
public static void main(String[] args) {
// Create a new student
Student student = new Student("Alice", "alice@example.com");

// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// Save the student
session.persist(student); // Hibernate will generate an INSERT SQL statement
transaction.commit();
session.close();
sessionFactory.close();
System.out.println("Student saved successfully!");
}
}

Read (Retrieve Data):

To fetch data, we use get() methods.

Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
public static void main(String[] args) {
// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.openSession();
// Fetch student with ID 1
Student student = session.get(Student.class, 1L);
if (student != null) {
System.out.println("Student Name: " + student.getName());
} else {
System.out.println("Student not found!");
}
session.close();
sessionFactory.close();
System.out.println("Student saved successfully!");
}
}

Update (Modify Data)

To update a record, we use the merge() method.

Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// Fetch student from DB
Student student = session.get(Student.class, 1L);
if (student != null) {
student.setEmail("newemail@example.com"); // Update email
session.merge(student); // Hibernate generates an UPDATE SQL statement
transaction.commit();
System.out.println("Student updated successfully!");
} else {
System.out.println("Student not found!");
}
session.close();
sessionFactory.close();
}
}

Delete (Remove Data)

To delete a record, we use the remove() method.

Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// Fetch student from DB
Student student = session.get(Student.class, 1L);

if (student != null) {
session.remove(student); // Hibernate generates DELETE SQL statement
transaction.commit();
System.out.println("Student deleted successfully!");
} else {
System.out.println("Student not found!");
}
session.close();
sessionFactory.close();
}
}

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.