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

Hibernate Bus Reservation System Guide

The document outlines the steps to create a Bus Reservation System using Hibernate and MySQL in Eclipse IDE. It includes instructions for setting up a MySQL database, configuring Hibernate, creating entity and DAO classes for CRUD operations, and testing the system with a main class. The document provides detailed code examples and explanations for each component involved in the system's development.

Uploaded by

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

Hibernate Bus Reservation System Guide

The document outlines the steps to create a Bus Reservation System using Hibernate and MySQL in Eclipse IDE. It includes instructions for setting up a MySQL database, configuring Hibernate, creating entity and DAO classes for CRUD operations, and testing the system with a main class. The document provides detailed code examples and explanations for each component involved in the system's development.

Uploaded by

saniyapathan0607
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Bus Reservation System using Hibernate Persistence in Eclipse IDE

• Create and configure a MySQL database table tailored for contact information.
• Set up the Hibernate configuration file to establish database connectivity.
• Develop entity classes using JPA annotations to map Java objects to database tables.
• Implement a Data Access Object (DAO) class for essential CRUD (Create, Read, Update,
Delete) operations.
• Test your contact management system with a main class demonstrating these functions.

Step 1: Creating the MySQL Table for Contacts


The first step in building the Bus Reservation System is to create the database table that will
store contact information. We will create a table named contacts in your MySQL database with
the following fields:

• id: An INT field, set as the primary key with AUTO_INCREMENT to uniquely identify
each contact.
• name: A VARCHAR(255) field to store the contact's full name.
• email: A VARCHAR(255) field for the contact’s email address.
• phone: A VARCHAR(20) field to save the contact’s phone number.
• address: A VARCHAR(255) field to hold the contact’s physical address.

To create this table,

CREATE TABLE contacts (


id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255),
phone VARCHAR(20),
address VARCHAR(255),
PRIMARY KEY (id)
);

Step 2: Setting up the Eclipse Project with Required


Libraries
1. Create a new Java Project:
– Open Eclipse IDE.
– Go to File > New > Java Project.
– Enter ContactManager as the project name.
– Keep the default JRE configuration and click Finish.
2. Create the package structure:
– Right-click on src folder.
– Select New > Package.
– Name the package [Link] and click Finish.
3. Add Hibernate and MySQL libraries:

To enable Hibernate ORM functionality and MySQL database connectivity, you must
include the necessary JAR files in your project build path. It is good practice to organize
these JARs inside a lib folder within your project:
– Create a new folder named lib at the root of the project.
– Download and place the following JAR files into the lib folder:
• Hibernate Core: [Link]
• Hibernate Commons Logging: [Link]
• Hibernate JPA API: [Link]
• MySQL JDBC Driver: [Link]
– In Eclipse, right-click your project and select Build Path > Configure Build Path.
– Under the Libraries tab, click Add JARs..., navigate to the lib folder, select all
JAR files, and click OK.
Project structure overview: After completing these steps, your project's basic structure should
look like this:

• ContactManager/ (root project folder)


• src/ – Source folder containing your Java packages, such as [Link].
• lib/ – Folder housing all required JAR libraries.
• [Link] – Hibernate configuration file (to be created in subsequent steps).

This organized layout ensures your source code, configuration files, and external libraries
remain cleanly separated, simplifying maintenance and development as you build your Bus
Reservation System.

Step 3: Creating Hibernate Configuration File


([Link])
The [Link] file is a crucial configuration file that instructs Hibernate how to connect
to your MySQL database and manage sessions. This XML file should be placed inside your
project's src folder or inside a resources folder if you have one, so that it is available in the
classpath at runtime. Hibernate automatically looks for this file when initializing.

Below is a complete example of the [Link] file configured for the Bus Reservation
System:

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"[Link]
<hibernate-configuration>
<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">[Link]</property>
<property name="[Link]">jdbc:mysql://localhost:3306/contactdb?
useSSL=false&serverTimezone=UTC</property>
<property name="[Link]">your_username</property>
<property name="[Link]">your_password</property>

<!-- SQL dialect for MySQL -->


<property name="dialect">[Link].MySQL8Dialect</property>

<!-- Show executed SQL statements in the console (useful for debugging) -->
<property name="show_sql">true</property>

<!-- Format the SQL displayed for readability -->


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

<!-- Automatically validate or update the schema (optional) -->


<property name="[Link]">update</property>

<!-- Enable second level cache (optional) -->


<!-- <property name="cache.provider_class">[Link]</property> -->

<!-- Specify annotated entity classes -->


<mapping class="[Link]"/>

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

Step 4: Creating the Contact Entity Class


([Link]) with JPA Annotations.

Annotations Overview
• @Entity: Marks the class as a persistent Java class, meaning it should be mapped to a
database table by Hibernate.
• @Table(name = "contacts"): Specifies the exact name of the table in the database that
this entity maps to, ensuring the mapping matches the table created in Step 1.
• @Id: Defines the primary key field of the entity. This uniquely identifies each contact
record.
• @GeneratedValue(strategy = [Link]): Specifies that the
primary key id is auto-incremented by the database (matching MySQL’s
AUTO_INCREMENT behavior).
• @Column: Maps each field to a table column with optional attributes such as nullable
and length. This maintains consistency and allows control over the database schema.

Below is the full annotated [Link] class with getter and setter methods for each field:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@Entity
@Table(name = "contacts")
public class Contact {

@Id
@GeneratedValue(strategy = [Link])
@Column(name = "id")
private int id;

@Column(name = "name", nullable = false, length = 255)


private String name;

@Column(name = "email", length = 255)


private String email;

@Column(name = "phone", length = 20)


private String phone;

@Column(name = "address", length = 255)


private String address;
// Default constructor (required by Hibernate)
public Contact() {
}

// Getter and setter for id


public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}

// Getter and setter for name


public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}

// Getter and setter for email


public String getEmail() {
return email;
}
public void setEmail(String email) {
[Link] = email;
}

// Getter and setter for phone


public String getPhone() {
return phone;
}
public void setPhone(String phone) {
[Link] = phone;
}
// Getter and setter for address
public String getAddress() {
return address;
}
public void setAddress(String address) {
[Link] = address;
}
}
.

Step 5: Creating the ContactDAO Class


([Link]) for CRUD Operations

Core DAO Methods Overview


• addContact(Contact contact): Saves a new contact record to the database.
• listContacts(): Retrieves all contact records as a list.
• updateContact(Contact contact): Updates an existing contact’s information.
• deleteContact(int contactId): Deletes a contact by its ID.

Full Source Code for [Link]


package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

public class ContactDAO {

private static SessionFactory sessionFactory;

static {
try {
// Build SessionFactory from [Link]
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
[Link]("Failed to create SessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
}

/**
* Adds a new contact to the database.
* @param contact the Contact object to be saved
*/
public void addContact(Contact contact) {
Transaction transaction = null;
try (Session session = [Link]()) {
transaction = [Link]();
[Link](contact); // Persist the contact entity
[Link]();
[Link]("Contact saved successfully: " + [Link]());
} catch (Exception e) {
if (transaction != null) [Link]();
[Link]();
}
}

/**
* Retrieves a list of all contacts from the database.
* @return List of Contact objects
*/
public List<Contact> listContacts() {
try (Session session = [Link]()) {
return [Link]("FROM Contact", [Link]).list();
} catch (Exception e) {
[Link]();
return null;
}
}

/**
* Updates an existing contact's details in the database.
* @param contact the Contact object containing updated information
*/
public void updateContact(Contact contact) {
Transaction transaction = null;
try (Session session = [Link]()) {
transaction = [Link]();
[Link](contact); // Update the contact entity
[Link]();
[Link]("Contact updated successfully: " + [Link]());
} catch (Exception e) {
if (transaction != null) [Link]();
[Link]();
}
}

/**
* Deletes the contact with the specified ID from the database.
* @param contactId the id of the contact to delete
*/
public void deleteContact(int contactId) {
Transaction transaction = null;
try (Session session = [Link]()) {
transaction = [Link]();
Contact contact = [Link]([Link], contactId);
if (contact != null) {
[Link](contact); // Remove the contact entity
[Link]("Contact deleted successfully: " + [Link]());
} else {
[Link]("Contact with ID " + contactId + " not found.");
}
[Link]();
} catch (Exception e) {
if (transaction != null) [Link]();
[Link]();
}
}

/**
* Closes the SessionFactory, releasing all resources.
* Call this method when the application is shutting down.
*/
public static void shutdown() {
if (sessionFactory != null) {
[Link]();
}
}
}

Step 6: Creating the Main Class ([Link]) to Test


CRUD Operations

Creating the [Link] Class


Inside the src/com/contactmanager directory, create a new Java class named Main and add the
following sample code:

package [Link];

import [Link];

public class Main {

public static void main(String[] args) {


ContactDAO contactDAO = new ContactDAO();

// 1. Add sample contacts


[Link]("Adding contacts...");
Contact contact1 = new Contact();
[Link]("Alice Johnson");
[Link]("[Link]@[Link]");
[Link]("123-456-7890");
[Link]("123 Maple Street, Springfield");
[Link](contact1);

Contact contact2 = new Contact();


[Link]("Bob Smith");
[Link]("[Link]@[Link]");
[Link]("555-987-6543");
[Link]("456 Oak Avenue, Metropolis");
[Link](contact2);

// 2. List all contacts


[Link]("\nListing all contacts:");
List<Contact> contacts = [Link]();
if (contacts != null) {
for (Contact c : contacts) {
[Link](
"ID: " + [Link]() +
", Name: " + [Link]() +
", Email: " + [Link]() +
", Phone: " + [Link]() +
", Address: " + [Link]()
);
}
}

// 3. Update a contact (change Bob's phone number)


[Link]("\nUpdating contact with ID 2...");
Contact contactToUpdate = [Link]()
.filter(c -> [Link]() == 2)
.findFirst()
.orElse(null);
if (contactToUpdate != null) {
[Link]("555-444-3333");
[Link](contactToUpdate);
} else {
[Link]("Contact with ID 2 not found for update.");
}

// 4. Delete a contact by ID (delete contact with ID 1)


[Link]("\nDeleting contact with ID 1...");
[Link](1);

// 5. List contacts again to verify changes


[Link]("\nListing all contacts after update and delete:");
List<Contact> updatedContacts = [Link]();
if (updatedContacts != null) {
for (Contact c : updatedContacts) {
[Link](
"ID: " + [Link]() +
", Name: " + [Link]() +
", Email: " + [Link]() +
", Phone: " + [Link]() +
", Address: " + [Link]()
);
}
}

// 6. Shutdown Hibernate SessionFactory to release resources


[Link]();
}
}

You might also like