[go: up one dir, main page]

0% found this document useful (0 votes)
7 views13 pages

Java Weekly Mock Interview Questions A1+A2 (12!07!2025)

The document outlines a mini project on JDBC for hospital management, explaining ACID properties essential for database transactions, illustrated with a banking example. It details how to implement these properties in Java using JDBC, along with a sample Java program for bank transactions. Additionally, it introduces the Hibernate framework, its history, and provides steps to set up Hibernate with a MySQL database, including POJO class implementation and configuration.

Uploaded by

likhitha0324
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)
7 views13 pages

Java Weekly Mock Interview Questions A1+A2 (12!07!2025)

The document outlines a mini project on JDBC for hospital management, explaining ACID properties essential for database transactions, illustrated with a banking example. It details how to implement these properties in Java using JDBC, along with a sample Java program for bank transactions. Additionally, it introduces the Hibernate framework, its history, and provides steps to set up Hibernate with a MySQL database, including POJO class implementation and configuration.

Uploaded by

likhitha0324
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/ 13

07/07/2025

Mini Project on JDBC ( Hospital Management )

08/07/2025

What Are ACID Properties?

ACID stands for:

Property Meaning

A Atomicity – all or nothing

C Consistency – data remains valid

I Isolation – concurrent safety

D Durability – changes are permanent

These are the fundamental properties of database transactions to ensure data integrity.

ACID Properties – Real-Time Banking Example

Suppose you transfer ₹1000 from Account A to Account B:

➤ Atomicity:

 Either both debit and credit succeed, or neither does.

 If debit succeeds but credit fails, rollback.

➤ Consistency:

 Before & after the transaction, the total amount in the system must remain the same.

➤ Isolation:

 While your transaction is happening, another transaction can’t see partial updates.

➤ Durability:
 Once the transaction is committed, even a power failure won't undo it.

How to Implement ACID in Java JDBC?

You use:

Method Purpose

conn.setAutoCommit(false) Turns off auto-commit (Atomicity)

conn.commit() Commits the transaction (Durability)

conn.rollback() Rolls back in case of failure (Atomicity)

Isolation Level (optional) For Isolation (conn.setTransactionIsolation(...))

Java Program: ACID Implementation using JDBC

This simulates a bank transfer between two accounts using ACID properties.

Database Table:

CREATE TABLE bank (

acc_no INT PRIMARY KEY,

name VARCHAR(50),

balance DOUBLE

);

INSERT INTO bank VALUES (101, 'Alice', 5000);

INSERT INTO bank VALUES (102, 'Bob', 3000);

Java Code:

import java.sql.*;

public class BankTransaction {

public static void main(String[] args) {

Connection con = null;

PreparedStatement debitStmt = null;

PreparedStatement creditStmt = null;\


try {

// Step 1 & 2: Load Driver & Get Connection

Class.forName("com.mysql.cj.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankdb", "root", "1234");

// Step 3: Turn off auto-commit for transaction

con.setAutoCommit(false); // Begin transaction

// Debit ₹1000 from Account 101

debitStmt = con.prepareStatement("UPDATE bank SET balance = balance - 1000 WHERE


acc_no = 101");

debitStmt.executeUpdate();

// Simulate error: int x = 10 / 0; // Uncomment to test rollback

// Credit ₹1000 to Account 102

creditStmt = con.prepareStatement("UPDATE bank SET balance = balance + 1000 WHERE


acc_no = 102");

creditStmt.executeUpdate();

// Step 4: Commit changes

con.commit(); // Durable + Consistent

System.out.println("Transaction Successful");

} catch (Exception e) {

try {

if (con != null) {

con.rollback(); // Undo if error (Atomicity)

System.out.println("Transaction Rolled Back");

} catch (SQLException ex) {

ex.printStackTrace();

e.printStackTrace();

} finally {

// Step 5: Close everything

try {

if (debitStmt != null) debitStmt.close();


if (creditStmt != null) creditStmt.close();

if (con != null) con.close();

System.out.println("🔌 Connection Closed");

} catch (Exception ex) {

ex.printStackTrace();

Output:

Transaction Successful

Connection Closed

If error occurs:

Transaction Rolled Back

Connection Closed

Summary: How Java Supports ACID

ACID Property JDBC Support

Atomicity setAutoCommit(false) + rollback()

Consistency Your business logic + DB constraints

Isolation setTransactionIsolation(...)

Durability commit() makes it permanent

09/07/2025

1. What is a Framework?
A framework is a pre-defined structure of reusable code that helps developers avoid writing
boilerplate logic.

Why Use a Framework?

 Saves time and effort.

 Follows best practices and design patterns.

 Reduces redundancy.

 Improves security and scalability.

2. What is Hibernate Framework?

Hibernate is an Object Relational Mapping (ORM) framework for Java that simplifies interaction with
databases.

Core Idea:

Hibernate maps Java objects to database tables without writing SQL queries manually.

Example:

Employee e = new Employee("Alice", 50000);

// Hibernate saves it directly to DB — no SQL required!

3. History of Hibernate

Version Year Notes

v1.0 2001 Created by Gavin King

v3.0 2005 Introduced annotations

v5.x 2016–2020 Better JPA support, performance

v6.x 2021–2024 Java 17+ support, performance boost

4. What is ORM (Object Relational Mapping)?

ORM is a programming technique that lets you map Java classes to database tables.
Java Object SQL Table

Employee class employee table

name field name column

emp.getName() SELECT name FROM...

5. Steps to Install and Use Hibernate in Eclipse

A. Download Hibernate JARs

You can either:

 Use Maven (recommended)

 OR manually download from hibernate.org

Maven Dependency (paste in pom.xml):

<dependencies>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.6.15.Final</version> <!-- or latest -->

</dependency>

<!-- JDBC Driver (MySQL example) -->

<dependency>

<groupId>mysql</groupId>

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

<version>8.0.33</version>

</dependency>

</dependencies>

B. If Using Non-Maven (Manually Add JARs):

1. Download:
o hibernate-core

o hibernate-commons-annotations

o hibernate-entitymanager

o mysql-connector-java

o Required dependencies (JTA, ANTLR, etc.)

2. In Eclipse:

o Right-click your project → Build Path → Configure Build Path

o Add External JARs → Select all Hibernate and MySQL JARs

Final Step: Create Hibernate Project Structure

Folder/File Purpose

hibernate.cfg.xml DB config (driver, URL, user, pwd)

Entity class Java class mapped to DB table

HibernateUtil.java Utility class for SessionFactory

TestMain.java Program to save/read entity

10/07/2025

 Create a MySQL database and table (student)

 Build a POJO class

 Set up the Hibernate configuration using XML (hibernate.cfg.xml)

1. Create MySQL Database & Table

Open your MySQL terminal or MySQL Workbench and run:

CREATE DATABASE hibernatedb;

USE hibernatedb;

CREATE TABLE student (

id INT PRIMARY KEY AUTO_INCREMENT,

name VARCHAR(100),
email VARCHAR(100)

);

2. What is a POJO Class?

A POJO (Plain Old Java Object) is a simple Java class used to represent data.
In Hibernate, POJOs are used as entities that map to database tables.

Features:

 Private variables (fields)

 Public getters and setters

 No business logic or inheritance required

3. POJO Class Implementation (Student.java)

package com.example;

public class Student {

private int id;

private String name;

private String email;

// Default constructor

public Student() {}

// Parameterized constructor

public Student(String name, String email) {

this.name = name;

this.email = email;

// Getters & 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; }


@Override

public String toString() {

return "Student [id=" + id + ", name=" + name + ", email=" + email + "]";

4. Hibernate XML Configuration (hibernate.cfg.xml)

Place this file in your project’s src/main/resources folder (or src/ if not using Maven):

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 5.3//EN"

"http://hibernate.org/dtd/hibernate-configuration-5.3.dtd">

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->

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

<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>

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

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

<!-- JDBC connection pool -->

<property name="connection.pool_size">5</property>

<!-- SQL dialect -->

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

<!-- Show SQL -->

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

<!-- Auto-create/update DB schema -->

<property name="hbm2ddl.auto">update</property>

<!-- Entity mapping -->

<mapping class="com.example.Student"/>

</session-factory>
</hibernate-configuration>

Replace your_password with your actual MySQL root password.

11/07/2025

Full Hibernate Example: Inserting Data from Java to MySQL

1. MySQL Setup

CREATE DATABASE hibernatedb;

USE hibernatedb;

CREATE TABLE student (

id INT PRIMARY KEY AUTO_INCREMENT,

name VARCHAR(100),

email VARCHAR(100)

);

2. POJO Class: Student.java

package com.example;

public class Student {

private int id;

private String name;

private String email;

public Student() {}

public Student(String name, String email) {

this.name = name;

this.email = email;

// Getters & 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; }

3. Hibernate Configuration File: hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 5.3//EN"

"http://hibernate.org/dtd/hibernate-configuration-5.3.dtd">

<hibernate-configuration>

<session-factory>

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

<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>

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

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

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

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

<property name="hbm2ddl.auto">update</property>

<mapping class="com.example.Student"/>

</session-factory>

</hibernate-configuration>

Replace your_password with your actual MySQL password.

4. Main Logic: Program1.java

package com.example;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class Program1 {

public static void main(String[] args) {


// Step 1: Create Configuration

Configuration cfg = new Configuration();

cfg.configure("hibernate.cfg.xml");

cfg.addAnnotatedClass(Student.class);

// Step 2: Create SessionFactory

SessionFactory factory = cfg.buildSessionFactory();

// Step 3: Open Session

Session session = factory.openSession();

// Step 4: Begin Transaction

session.beginTransaction();

// Step 5: Insert Data

Student student = new Student("John Doe", "john@example.com");

session.save(student);

// Step 6: Commit and Close

session.getTransaction().commit();

session.close();

factory.close();

System.out.println("Data inserted successfully!");

Required Dependencies (If using Maven)

Add this to your pom.xml:

<dependencies>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.6.15.Final</version>

</dependency>

<dependency>

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

<version>8.0.33</version>

</dependency>

</dependencies>

Final Notes:

 You’ve completed all 6 core Hibernate steps (Configure → BuildFactory → OpenSession →


BeginTransaction → Save → Commit).

 Make sure you have the JARs or Maven dependencies configured.

 Use Eclipse's Run As → Java Application to test.

You might also like