Introduction
3.
1. Employee Entity Class (Employee.java)
package com.example;
import javax.persistence.*;
@Entity
@Table(name = "Employee")
public class Employee {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
private int id;
@Column(name = "Name", nullable = false)
private String name;
@Column(name = "Designation")
private String designation;
@Column(name = "Salary")
private double salary;
// Constructors
public Employee() {}
public Employee(String name, String designation, double salary) {
this.name = name;
this.designation = designation;
this.salary = salary;
}
// Getters & Setters
public int getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDesignation() { return designation; }
public void setDesignation(String designation) { this.designation =
designation; }
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary; }
}
2. Hibernate Configuration (hibernate.cfg.xml)(insider resource folder)
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Connection Settings -->
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property
name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Automatically creates table if not exists -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Show SQL in console -->
<property name="hibernate.show_sql">true</property>
<!-- Mapping class -->
<mapping class="com.example.Employee"/>
</session-factory>
</hibernate-configuration>
3. Main Class (MainApp.java)
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class MainApp {
public static void main(String[] args) {
// Load Hibernate config
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Insert 5 employees
Employee e1 = new Employee("Alice", "Developer", 50000);
Employee e2 = new Employee("Bob", "Manager", 75000);
Employee e3 = new Employee("Charlie", "Tester", 40000);
Employee e4 = new Employee("David", "HR", 45000);
Employee e5 = new Employee("Eve", "Architect", 90000);
session.save(e1);
session.save(e2);
session.save(e3);
session.save(e4);
session.save(e5);
tx.commit();
session.close();
factory.close();
System.out.println("✅ 5 Employee records inserted successfully!");
}
}
4.
Using Hibernate create a Product table in the backend and insert 5 Product
objects into the database.
The following are the details of theProduct table.
ProductName varchar2
ProductId Number
Price Number
The value of the ProductId should be taken from a sequnce which is created at
the back end
[ Hint : generator class=sequence ]
Oracle DB (SQL*Plus or SQL Developer) and create a sequence:
CREATE SEQUENCE product_seq
START WITH 1
INCREMENT BY 1
NOCACHE
NOCYCLE;
Product Entity (Product.java)
package com.example;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "Product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"product_seq_gen")
@SequenceGenerator(name = "product_seq_gen", sequenceName = "product_seq",
allocationSize = 1)
private int productId;
@Column(name = "ProductName", nullable = false)
private String productName;
@Column(name = "Price")
private double price;
// Constructors
public Product() {}
public Product(String productName, double price) {
this.productName = productName;
this.price = price;
}
// Getters & Setters
public int getProductId() { return productId; }
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName =
productName; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
Hibernate Configuration (hibernate.cfg.xml)
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Oracle Connection -->
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property
name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Hibernate Settings -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<!-- Mapping -->
<mapping class="com.example.Product"/>
</session-factory>
</hibernate-configuration>
Main Class (MainApp.java)
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class MainApp {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Insert 5 Products
Product p1 = new Product("Laptop", 55000);
Product p2 = new Product("Mobile", 20000);
Product p3 = new Product("Tablet", 15000);
Product p4 = new Product("Headphones", 3000);
Product p5 = new Product("Smartwatch", 7000);
session.save(p1);
session.save(p2);
session.save(p3);
session.save(p4);
session.save(p5);
tx.commit();
session.close();
factory.close();
System.out.println("✅ 5 Products inserted successfully!");
}
}
Objects
2.Write a Hibernate Program to Delete a Flower with its Id from the table that
you have created earlier. If there is no Flower with that id exists, then an
appropriate error message needs to be stored to the user.
Flower Entity (Flower.java)
package com.example;
import javax.persistence.*;
@Entity
@Table(name = "Flower")
public class Flower {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "FlowerName", nullable = false)
private String name;
@Column(name = "Price")
private double price;
// Constructors
public Flower() {}
public Flower(String name, double price) {
this.name = name;
this.price = price;
}
// Getters & Setters
public int getId() { return 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; }
}
Hibernate Configuration (hibernate.cfg.xml)
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties -->
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property
name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Hibernate settings -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<!-- Mapping -->
<mapping class="com.example.Flower"/>
</session-factory>
</hibernate-configuration>
Main Program to Delete Flower (DeleteFlowerApp.java)
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DeleteFlowerApp {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
int flowerIdToDelete = 3; // Change this Id for testing
Flower flower = session.get(Flower.class, flowerIdToDelete);
if (flower != null) {
session.delete(flower);
System.out.println("✅ Flower with ID " + flowerIdToDelete + " deleted
successfully!");
} else {
System.out.println("❌ Error: No Flower found with ID " +
flowerIdToDelete);
}
tx.commit();
session.close();
factory.close();
}
}
Hibernate 3 with Annotations
1.
Write a Hibernate Program which makes using of all the annotations @Entity,
@Table, @Id, @Column to create the mapping for the following table Car_Details
RegNo char(5)
Model varchar2(20)
Color varchar2(10)
Manufacturer varchar2(20)
Car Entity (Car.java)
package com.example;
import javax.persistence.*;
@Entity
@Table(name = "Car_Details")
public class Car {
@Id
@Column(name = "RegNo", length = 5, nullable = false)
private String regNo;
@Column(name = "Model", length = 20, nullable = false)
private String model;
@Column(name = "Color", length = 10)
private String color;
@Column(name = "Manufacturer", length = 20)
private String manufacturer;
// Constructors
public Car() {}
public Car(String regNo, String model, String color, String manufacturer) {
this.regNo = regNo;
this.model = model;
this.color = color;
this.manufacturer = manufacturer;
}
// Getters and Setters
public String getRegNo() { return regNo; }
public void setRegNo(String regNo) { this.regNo = regNo; }
public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public String getManufacturer() { return manufacturer; }
public void setManufacturer(String manufacturer) { this.manufacturer =
manufacturer; }
@Override
public String toString() {
return "Car [RegNo=" + regNo + ", Model=" + model + ", Color=" + color + ",
Manufacturer=" + manufacturer + "]";
}
}
Hibernate Configuration (hibernate.cfg.xml)
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection -->
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property
name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Hibernate properties -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<!-- Mapping -->
<mapping class="com.example.Car"/>
</session-factory>
</hibernate-configuration>
Insert Records (CarApp.java)
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class CarApp {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Creating Car objects
Car c1 = new Car("C1001", "Swift", "Red", "Maruti");
Car c2 = new Car("C1002", "City", "Black", "Honda");
Car c3 = new Car("C1003", "i20", "Blue", "Hyundai");
// Saving objects
session.save(c1);
session.save(c2);
session.save(c3);
tx.commit();
session.close();
factory.close();
System.out.println("✅ Cars inserted successfully into Car_Details table.");
}
}
2.
Car.java (Entity Class)
package com.example;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "Car_Details")
public class Car {
@Id
@Column(name = "RegNo", length = 5)
private String regNo;
@Column(name = "Model", length = 20)
private String model;
@Column(name = "Color", length = 10)
private String color;
@Column(name = "Manufacturer", length = 20)
private String manufacturer;
// Parameterized constructor
public Car(String regNo, String model, String color, String manufacturer) {
this.regNo = regNo;
this.model = model;
this.color = color;
this.manufacturer = manufacturer;
}
// Default constructor (Hibernate needs it)
public Car() {}
// Getters and Setters
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
@Override
public String toString() {
return "Car [RegNo=" + regNo + ", Model=" + model + ", Color=" + color + ",
Manufacturer=" + manufacturer + "]";
}
}
hibernate.cfg.xml in src/main/source
<?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>
<!-- Database connection settings -->
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">oracle</property>
<!-- JDBC dialect -->
<property
name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Automatically create/update tables -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Show SQL in console -->
<property name="hibernate.show_sql">true</property>
<!-- Mapping class -->
<mapping class="com.example.Car"/>
</session-factory>
</hibernate-configuration>
CarApp.java (Main Program)
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.List;
public class CarApp {
public static void main(String[] args) {
// Load Hibernate configuration
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Insert records
Car car1 = new Car("AB234", "Vento", "White", "Volkswagen");
Car car2 = new Car("AC345", "Corolla", "Black", "Toyota");
Car car3 = new Car("AB123", "Polo", "Silver", "Volkswagen");
session.save(car1);
session.save(car2);
session.save(car3);
tx.commit();
// Fetch & display all cars
List<Car> cars = session.createQuery("from Car", Car.class).list();
System.out.println("\n✅ Cars in database:");
cars.forEach(System.out::println);
session.close();
factory.close();
}
}
HQL
2. Write a Hibernate program to display only the RegNo and the Manufacturer's name
in the above program
Car.java (Entity Class)
package com.example;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "Car_Details")
public class Car {
@Id
@Column(name = "RegNo", length = 10)
private String regNo;
@Column(name = "Model", length = 20)
private String model;
@Column(name = "Color", length = 10)
private String color;
@Column(name = "Manufacturer", length = 20)
private String manufacturer;
// Default constructor
public Car() {}
// Parameterized constructor
public Car(String regNo, String model, String color, String manufacturer) {
this.regNo = regNo;
this.model = model;
this.color = color;
this.manufacturer = manufacturer;
}
// Getters & Setters
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
}
CarApp.java (Main Program)
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.List;
public class CarApp {
public static void main(String[] args) {
// Load Hibernate configuration
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.addAnnotatedClass(Car.class);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Insert sample data
Car c1 = new Car("AB234", "Vento", "White", "Volkswagen");
Car c2 = new Car("AC345", "Corolla", "Black", "Toyota");
Car c3 = new Car("AB123", "Polo", "Silver", "Volkswagen");
session.persist(c1);
session.persist(c2);
session.persist(c3);
tx.commit();
// Fetch only RegNo and Manufacturer
session.beginTransaction();
List<Object[]> cars = session.createQuery(
"select c.regNo, c.manufacturer from Car c", Object[].class)
.getResultList();
System.out.println("\n✅ Car RegNo and Manufacturer:");
for (Object[] row : cars) {
String regNo = (String) row[0];
String manufacturer = (String) row[1];
System.out.println("RegNo: " + regNo + " | Manufacturer: " +
manufacturer);
}
session.getTransaction().commit();
session.close();
factory.close();
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<!-- JDBC dialect -->
<property
name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<!-- Auto table creation -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Show SQL in console -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
</session-factory>
</hibernate-configuration>
3.
Write a Hibernate program which will ask the user to enter a registration
number and display the details of that Vehicle. Assign the value to the query
using a label.
Car.java
package com.example;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "Car_Details")
public class Car {
@Id
@Column(name = "RegNo", length = 10)
private String regNo;
@Column(name = "Model", length = 20)
private String model;
@Column(name = "Color", length = 10)
private String color;
@Column(name = "Manufacturer", length = 20)
private String manufacturer;
public Car() {}
public Car(String regNo, String model, String color, String manufacturer) {
this.regNo = regNo;
this.model = model;
this.color = color;
this.manufacturer = manufacturer;
}
// Getters & Setters
public String getRegNo() { return regNo; }
public void setRegNo(String regNo) { this.regNo = regNo; }
public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public String getManufacturer() { return manufacturer; }
public void setManufacturer(String manufacturer) { this.manufacturer =
manufacturer; }
}
CarSearchApp.java (Main Program)
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.Scanner;
public class CarSearchApp {
public static void main(String[] args) {
// Load Hibernate config
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.addAnnotatedClass(Car.class);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Registration Number: ");
String regNoInput = sc.nextLine();
// Begin transaction
Transaction tx = session.beginTransaction();
// HQL with parameter (label binding)
String hql = "from Car c where c.regNo = :regno";
Car car = session.createQuery(hql, Car.class)
.setParameter("regno", regNoInput)
.uniqueResult();
if (car != null) {
System.out.println("\n✅ Vehicle Details:");
System.out.println("RegNo: " + car.getRegNo());
System.out.println("Model: " + car.getModel());
System.out.println("Color: " + car.getColor());
System.out.println("Manufacturer: " + car.getManufacturer());
} else {
System.out.println("\n⚠️ No vehicle found with RegNo: " + regNoInput);
}
tx.commit();
session.close();
factory.close();
sc.close();
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- DB Connection -->
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property
name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
4.
Write a Hibernate program to display only the Manufacturer's names which are
starting with 'V' from above table
Car.java
package com.example;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "Car_Details")
public class Car {
@Id
@Column(name = "RegNo", length = 10)
private String regNo;
@Column(name = "Model", length = 20)
private String model;
@Column(name = "Color", length = 10)
private String color;
@Column(name = "Manufacturer", length = 20)
private String manufacturer;
public Car() {}
public Car(String regNo, String model, String color, String manufacturer) {
this.regNo = regNo;
this.model = model;
this.color = color;
this.manufacturer = manufacturer;
}
// Getters & Setters
public String getRegNo() { return regNo; }
public void setRegNo(String regNo) { this.regNo = regNo; }
public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public String getManufacturer() { return manufacturer; }
public void setManufacturer(String manufacturer) { this.manufacturer =
manufacturer; }
}
ManufacturerSearchApp.java
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.List;
public class ManufacturerSearchApp {
public static void main(String[] args) {
// Load Hibernate config
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.addAnnotatedClass(Car.class);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// HQL Query - only manufacturers starting with 'V'
String hql = "select c.manufacturer from Car c where c.manufacturer
like :prefix";
List<String> manufacturers = session.createQuery(hql, String.class)
.setParameter("prefix", "V%")
.getResultList();
System.out.println("\n✅ Manufacturers starting with 'V':");
if (manufacturers.isEmpty()) {
System.out.println("⚠️ No manufacturer found starting with V");
} else {
for (String m : manufacturers) {
System.out.println(m);
}
}
tx.commit();
session.close();
factory.close();
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- DB Connection -->
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property
name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
6.
Write a Hibernate program to display total count of cars based on Reg No [Hint:
Use Criteria Query ]
Car.java
package com.example;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "Car_Details")
public class Car {
@Id
@Column(name = "RegNo", length = 10)
private String regNo;
@Column(name = "Model", length = 20)
private String model;
@Column(name = "Color", length = 10)
private String color;
@Column(name = "Manufacturer", length = 20)
private String manufacturer;
public Car() {}
public Car(String regNo, String model, String color, String manufacturer) {
this.regNo = regNo;
this.model = model;
this.color = color;
this.manufacturer = manufacturer;
}
// Getters and Setters
public String getRegNo() { return regNo; }
public void setRegNo(String regNo) { this.regNo = regNo; }
public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public String getManufacturer() { return manufacturer; }
public void setManufacturer(String manufacturer) { this.manufacturer =
manufacturer; }
}
CarCountApp.java (Main Program with Criteria Query)
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
public class CarCountApp {
public static void main(String[] args) {
// Load Hibernate config
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.addAnnotatedClass(Car.class);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Create CriteriaBuilder
CriteriaBuilder cb = session.getCriteriaBuilder();
// Create CriteriaQuery<Long> for COUNT
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<Car> root = cq.from(Car.class);
// Select COUNT(RegNo)
cq.select(cb.count(root.get("regNo")));
// Execute query
Long totalCars = session.createQuery(cq).getSingleResult();
System.out.println("\n✅ Total number of cars in Car_Details table: " +
totalCars);
tx.commit();
session.close();
factory.close();
}
}
Mappings
2.
Make another class called MultiCarOwner program to persist the following class
object using Collection Mapping of one owner to many cars mapping:
public class CarOwner {
private int OnnerId;
private String OnerName;
private List cars;
}
Car.java
package com.example;
import jakarta.persistence.*;
@Entity
@Table(name = "Car_Details")
public class Car {
@Id
@Column(name = "RegNo", length = 10)
private String regNo;
@Column(name = "Model", length = 20)
private String model;
@Column(name = "Color", length = 10)
private String color;
@Column(name = "Manufacturer", length = 20)
private String manufacturer;
// Many cars belong to one owner
@ManyToOne
@JoinColumn(name = "owner_id")
private CarOwner owner;
public Car() {}
public Car(String regNo, String model, String color, String manufacturer) {
this.regNo = regNo;
this.model = model;
this.color = color;
this.manufacturer = manufacturer;
}
// Getters & Setters
public String getRegNo() { return regNo; }
public void setRegNo(String regNo) { this.regNo = regNo; }
public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public String getManufacturer() { return manufacturer; }
public void setManufacturer(String manufacturer) { this.manufacturer =
manufacturer; }
public CarOwner getOwner() { return owner; }
public void setOwner(CarOwner owner) { this.owner = owner; }
}
CarOwner.java
package com.example;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "CarOwner")
public class CarOwner {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int ownerId;
@Column(name = "OwnerName", length = 30)
private String ownerName;
// One owner → many cars
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Car> cars = new ArrayList<>();
public CarOwner() {}
public CarOwner(String ownerName) {
this.ownerName = ownerName;
}
// Helper method to add cars
public void addCar(Car car) {
cars.add(car);
car.setOwner(this);
}
// Getters & Setters
public int getOwnerId() { return ownerId; }
public void setOwnerId(int ownerId) { this.ownerId = ownerId; }
public String getOwnerName() { return ownerName; }
public void setOwnerName(String ownerName) { this.ownerName = ownerName; }
public List<Car> getCars() { return cars; }
public void setCars(List<Car> cars) { this.cars = cars; }
}
MultiCarOwner.java
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class MultiCarOwner {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.addAnnotatedClass(Car.class);
cfg.addAnnotatedClass(CarOwner.class);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Create owner
CarOwner owner1 = new CarOwner("Rajesh Kumar");
// Create cars
Car car1 = new Car("KA01AB1234", "Polo", "White", "Volkswagen");
Car car2 = new Car("KA02BC5678", "Vento", "Black", "Volkswagen");
Car car3 = new Car("KA03CD9101", "Corolla", "Silver", "Toyota");
// Assign cars to owner
owner1.addCar(car1);
owner1.addCar(car2);
owner1.addCar(car3);
// Persist owner (cascade will save cars too)
session.persist(owner1);
tx.commit();
session.close();
factory.close();
System.out.println("\n✅ Owner and cars saved successfully!");
}
}
4.
Write an Employee class and Passport class such that, one employee object
should hold only one passport object (one-to-one).
Implement a client code such that when we save or delete Employee object,
automatically passport object should be stored or deleted in a related table.
Note: you can add any appropriate class members
Employee.java
package com.example;
import jakarta.persistence.*;
@Entity
@Table(name = "Employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int empId;
@Column(name = "EmpName", length = 50, nullable = false)
private String empName;
@Column(name = "Department", length = 30)
private String department;
// One-to-One with Passport
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "passport_id", referencedColumnName = "passportId")
private Passport passport;
public Employee() {}
public Employee(String empName, String department) {
this.empName = empName;
this.department = department;
}
// Getters & Setters
public int getEmpId() { return empId; }
public void setEmpId(int empId) { this.empId = empId; }
public String getEmpName() { return empName; }
public void setEmpName(String empName) { this.empName = empName; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; }
public Passport getPassport() { return passport; }
public void setPassport(Passport passport) { this.passport = passport; }
}
Passport.java
package com.example;
import jakarta.persistence.*;
@Entity
@Table(name = "Passport")
public class Passport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int passportId;
@Column(name = "PassportNumber", unique = true, nullable = false, length = 15)
private String passportNumber;
@Column(name = "Country", length = 30)
private String country;
public Passport() {}
public Passport(String passportNumber, String country) {
this.passportNumber = passportNumber;
this.country = country;
}
// Getters & Setters
public int getPassportId() { return passportId; }
public void setPassportId(int passportId) { this.passportId = passportId; }
public String getPassportNumber() { return passportNumber; }
public void setPassportNumber(String passportNumber) { this.passportNumber =
passportNumber; }
public String getCountry() { return country; }
public void setCountry(String country) { this.country = country; }
}
EmployeePassportClient.java
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmployeePassportClient {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.addAnnotatedClass(Employee.class);
cfg.addAnnotatedClass(Passport.class);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Create Employee and Passport
Passport p1 = new Passport("M1234567", "India");
Employee e1 = new Employee("Amit Sharma", "IT");
e1.setPassport(p1);
// Saving Employee (will also save Passport due to cascade)
session.persist(e1);
tx.commit();
System.out.println("\n✅ Employee and Passport saved!");
// --- Now test delete ---
session.beginTransaction();
Employee emp = session.get(Employee.class, e1.getEmpId());
if (emp != null) {
session.remove(emp); // also deletes passport due to orphanRemoval =
true
System.out.println("🗑 Employee and Passport deleted!");
}
session.getTransaction().commit();
session.close();
factory.close();
}
}
5.
Convert the Employee class with address class such that, one employee object
should have only one address object (one-to-one). As a Component Mapping Such
that there is only one employee table and the address details are added as
columns to the Employee table
Address.java
package com.example;
import jakarta.persistence.Embeddable;
@Embeddable
public class Address {
private String street;
private String city;
private String state;
private String zipcode;
public Address() {}
public Address(String street, String city, String state, String zipcode) {
this.street = street;
this.city = city;
this.state = state;
this.zipcode = zipcode;
}
// Getters & Setters
public String getStreet() { return street; }
public void setStreet(String street) { this.street = street; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public String getZipcode() { return zipcode; }
public void setZipcode(String zipcode) { this.zipcode = zipcode; }
}
Employee.java
package com.example;
import jakarta.persistence.*;
@Entity
@Table(name = "Employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int empId;
@Column(name = "EmpName", length = 50, nullable = false)
private String empName;
@Column(name = "Department", length = 30)
private String department;
// Embedded Address (will be flattened into Employee table)
@Embedded
private Address address;
public Employee() {}
public Employee(String empName, String department, Address address) {
this.empName = empName;
this.department = department;
this.address = address;
}
// Getters & Setters
public int getEmpId() { return empId; }
public void setEmpId(int empId) { this.empId = empId; }
public String getEmpName() { return empName; }
public void setEmpName(String empName) { this.empName = empName; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; }
public Address getAddress() { return address; }
public void setAddress(Address address) { this.address = address; }
}
EmployeeClient.java
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmployeeClient {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.addAnnotatedClass(Employee.class);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Create Employee with Address
Address addr = new Address("MG Road", "Bangalore", "Karnataka", "560001");
Employee emp = new Employee("Raj Kumar", "HR", addr);
session.persist(emp);
tx.commit();
System.out.println("\n✅ Employee with Address saved!");
session.close();
factory.close();
}
}