0% found this document useful (0 votes)
14 views16 pages

JV Updated

Uploaded by

Tejas Khadke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views16 pages

JV Updated

Uploaded by

Tejas Khadke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

23.

Create a Java application using Hibernate to perform CRUD operations on a Student


entity. Instructions: 1. Define a Student entity with fields id, name, email, and age. 2.
Configure Hibernate to connect to a database (MySQL or H2). 3. Implement methods to
perform CRUD operations: o createStudent(Student student) o readStudent(int
studentId) o updateStudent(Student student) o deleteStudent(int studentId) 4. Test the
CRUD operations by creating instances of Student and invoking these methods.

Pom.xml
<dependencies>

<!-- Hibernate Core -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.4.32.Final</version> <!-- Use the latest version -->

</dependency>

<!-- MySQL Connector/J -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.26</version> <!-- Use the latest version -->

</dependency>

<!-- SLF4J (for logging) -->

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

<version>1.7.32</version>

</dependency>

<!-- SLF4J with Logback (Logging Implementation) -->

<dependency>
<groupId>org.slf4j</groupId>

<artifactId>slf4j-log4j12</artifactId>

<version>1.7.32</version>

</dependency>

</dependencies>

Student.java

package com.example.hibernate;

import javax.persistence.Entity;
import
javax.persistence.GeneratedValue;
import
javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity public
class Student {

@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY) private int id; private
String name; private String email; private int age; //
Default constructor public Student() {} // Constructor
with parameters

public Student(String name, String email, int


age) { this.name = name; this.email =
email; this.age = age;

// Getters and Setters


public int getId() {
return id;

public void setId(int 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 +
"]";

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration
DTD

3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- JDBC Database connection settings -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

<property

name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

<property

name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_db</propert
y> <!--

Replace with your database URL -->

<property name="hibernate.connection.username">root</property> <!-- Replace


with your database username -->

<property name="hibernate.connection.password">password</property> <!--


Replace with your database password -->

<!-- JDBC connection pool settings -->

<property name="hibernate.c3p0.min_size">5</property>

<property name="hibernate.c3p0.max_size">20</property>

<property name="hibernate.c3p0.timeout">300</property>

<property name="hibernate.c3p0.max_statements">50</property>

<property name="hibernate.c3p0.idle_test_period">3000</property>

<!-- Specify the JDBC driver class -->

<property name="hibernate.show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->

<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Echo all executed queries to stdout -->

<property name="hibernate.format_sql">true</property>

<!-- Enable Hibernate's automatic session context management -->

<property name="hibernate.current_session_context_class">thread</property>

<!-- Disable the second-level cache -->

<property

name="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvid
er</pro perty>

</session-factory>

</hibernate-configuration>

StudentDAO.java

package com.example.hibernate;

import org.hibernate.Session;
import
org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

public class StudentDAO {


private SessionFactory
factory; public
StudentDAO() { factory =
new

Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buil
dSessi onFactory();

// Create a new student public void


createStudent(Student student) { Session session
= factory.getCurrentSession(); Transaction
transaction = session.beginTransaction();
session.save(student);

transaction.commit();

// Read a student by id public Student


readStudent(int studentId) { Session
session = factory.getCurrentSession();

Transaction transaction = session.beginTransaction();

Student student = session.get(Student.class,


studentId); transaction.commit(); return
student;

// Update student details public void


updateStudent(Student student) { Session
session = factory.getCurrentSession();
Transaction transaction = session.beginTransaction();
session.update(student);

transaction.commit();

// Delete student by id public void


deleteStudent(int studentId) { Session
session = factory.getCurrentSession();

Transaction transaction = session.beginTransaction();


Student student = session.get(Student.class, studentId);
if (student != null) {

session.delete(student);

transaction.commit();

// Close session factory


public void close() {
factory.close();
}

MainApp.java

package com.example.hibernate;

public class MainApp {

public static void main(String[] args) {

StudentDAO studentDAO = new StudentDAO();

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


studentDAO.createStudent(newStudent);

Student student = studentDAO.readStudent(newStudent.getId());

System.out.println("Retrieved Student: " + student);

student.setAge(26);

studentDAO.updateStudent(student);

System.out.println("Updated Student: " + student);

studentDAO.deleteStudent(student.getId());

System.out.println("Student deleted with id: " + student.getId());

studentDAO.close();

Output:-
25. Create a Java application using Hibernate to perform a CRUD operation using
Hibernate Query Language (HQL). Instructions: 1. Define a Product entity with fields id,
name, price, and quantity. 2. Implement methods to: o Insert new Product objects into
the database. o Retrieve all Product objects using HQL. o Update a Product object. o
Delete a Product object by ID. 3. Test the CRUD operations by creating instances of
Product and invoking these methods.

Pom.xml
<dependencies>

<!-- Hibernate Core Dependency -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.5.6.Final</version>

</dependency>

<!-- H2 Database Dependency (for testing) -->

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<version>1.4.200</version>

<scope>runtime</scope>

</dependency>

<!-- JPA (Java Persistence API) for Hibernate -->

<dependency>

<groupId>javax.persistence</groupId>

<artifactId>javax.persistence-api</artifactId>

<version>2.2</version>

</dependency>

<!-- SLF4J Logging Dependency (for Hibernate logs) -->


<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

<version>1.7.32</version>

</dependency>

<!-- Logback for SLF4J Implementation -->

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-log4j12</artifactId>

<version>1.7.32</version>

</dependency>

</dependencies>

Product.java package
com.example.model; import
javax.persistence.Entity;
import javax.persistence.Id;
import
javax.persistence.Table;
@Entity

@Table(name = "product")
public class Product

@Id private int


id; private String
name; private
double price;
private int quantity;

// Constructors, getters, and setters


public Product() {}

public Product(int id, String name, double price, int


quantity) { this.id = id; this.name = name;
this.price = price;
this.quantity = quantity;

public int getId() {


return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public double getPrice() {

return price;

public void setPrice(double price) {

this.price = price;

public int getQuantity() {


return quantity;

public void setQuantity(int quantity) {

this.quantity = quantity;

@Override

public String toString() {


return "Product{id=" + id + ", name='" + name + "', price=" + price + ", quantity=" +
quantity + "}";

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration


DTD

3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- JDBC Database connection settings -->

<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>

<property name="hibernate.connection.driver_class">org.h2.Driver</property>

<property name="hibernate.connection.url">jdbc:h2:mem:testdb</property>

<property name="hibernate.connection.username">sa</property>

<property name="hibernate.connection.password">password</property>

<!-- JDBC connection pool settings -->

<property name="hibernate.c3p0.min_size">5</property>

<property name="hibernate.c3p0.max_size">20</property>

<!-- Specify dialect -->

<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>

<!-- Enable Hibernate's automatic session context management -->

<property name="hibernate.current_session_context_class">thread</property>

<!-- Echo all executed SQL to stdout -->

<property name="hibernate.show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->

<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mention annotated class -->

<mapping class="com.example.model.Product"/>

</session-factory>

</hibernate-configuration>

ProductDAO.java package
com.example.dao; import
com.example.model.Product;
import org.hibernate.Session;
import
org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.query.Query;

import java.util.List; public class ProductDAO {


private SessionFactory sessionFactory; public
ProductDAO(SessionFactory sessionFactory) {

this.sessionFactory = sessionFactory;

public void createProduct(Product product) {


Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(product); transaction.commit();
session.close();

public List<Product> getAllProducts() {

Session session = sessionFactory.openSession();

Query<Product> query = session.createQuery("FROM Product", Product.class);

List<Product> products = query.list();

session.close();
return products;

}
public void updateProduct(Product product) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.update(product); transaction.commit();
session.close();

public void deleteProduct(int productId) {


Session session = sessionFactory.openSession();

Transaction transaction =
session.beginTransaction(); Product product =
session.get(Product.class, productId); if (product !=
null) { session.delete(product);

System.out.println("Product deleted with ID: " + productId);

}
transaction.commit(
);

session.close();

HibernateUtil.java package
com.example.util; import
org.hibernate.SessionFactory;
import
org.hibernate.cfg.Configuration;
public class HibernateUtil {

private static SessionFactory


sessionFactory; static { try {

sessionFactory = new

Configuration().configure("hibernate.cfg.xml").buildSessionFacto
ry(); } catch (Exception e) { e.printStackTrace();

public static SessionFactory getSessionFactory() {


return sessionFactory;

public static void shutdown() {

getSessionFactory().close();

Main.java package com.example;


import
com.example.dao.ProductDAO;
import
com.example.model.Product;
import
com.example.util.HibernateUtil;
import
org.hibernate.SessionFactory;

import java.util.List;
public class Main {

public static void main(String[] args) {

// Get Hibernate SessionFactory

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

// Create DAO instance

ProductDAO productDAO = new ProductDAO(sessionFactory);

// Insert new product

Product product1 = new Product(1, "Product1", 100.0, 10);


productDAO.createProduct(product1);

// Retrieve all products

List<Product> products = productDAO.getAllProducts();

System.out.println("All Products: ");


for (Product product : products) {

System.out.println(product);

}
// Update a product

Product productToUpdate = products.get(0);


productToUpdate.setPrice(120.0);

productDAO.updateProduct(productToUpdate);

// Delete a product by ID
productDAO.deleteProduct(1); // Retrieve all
products after deletion products =
productDAO.getAllProducts();
System.out.println("All Products After Deletion: ");
for (Product product : products) {

System.out.println(product);

// Shutdown Hibernate

HibernateUtil.shutdown();

Output:-

You might also like