0% found this document useful (0 votes)
9 views26 pages

Unit V

This document outlines the steps to set up a Java development environment for creating RESTful APIs using Spring Boot, Hibernate, and MySQL. It includes instructions for installing necessary tools, creating a Spring Boot project, defining models and DAOs, and implementing CRUD operations. Additionally, it provides code examples for entity classes, DAO implementations, and controller setup.

Uploaded by

Kalyan Ram
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)
9 views26 pages

Unit V

This document outlines the steps to set up a Java development environment for creating RESTful APIs using Spring Boot, Hibernate, and MySQL. It includes instructions for installing necessary tools, creating a Spring Boot project, defining models and DAOs, and implementing CRUD operations. Additionally, it provides code examples for entity classes, DAO implementations, and controller setup.

Uploaded by

Kalyan Ram
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/ 26

UNIT-5 Web Services for the APIs

1. Setting up Environment

You need to set up the environment with the following tools and technologies:

- JDK: Java Development Kit (JDK) version 8 or later

- Maven: Dependency management tool (or Gradle, if preferred)

- MySQL: Database server

- IDE: Eclipse/IntelliJ IDEA (or any Java IDE)

- Hibernate: ORM (Object-Relational Mapping) framework

- Spring Boot: Framework for setting up RESTful APIs easily

- Postman or curl: For testing the APIs

# Steps to Set up the Environment:

1. Install JDK: Make sure you have JDK 8 or later installed on your machine.

- You can download it from [Oracle's website](https://www.oracle.com/java/technologies/javase-


jdk11-downloads.html).

2. Install MySQL: Download and install MySQL. You can also use a local MySQL database, or a cloud
service like AWS RDS or Azure Database.

3. Install IDE: You can use IntelliJ IDEA, Eclipse, or any preferred Java IDE.

4. Install Maven: [Install Maven](https://maven.apache.org/install.html), or use the Maven integration


in your IDE.

---
2. Create a New Spring Boot Project

You can create a Spring Boot project either manually or by using Spring Initializr.

# Using Spring Initializr:

- Visit [Spring Initializr](https://start.spring.io/)

- Choose `Maven Project`, `Java`, and a suitable Spring Boot version.

- Add the following dependencies:

- Spring Web

- Spring Data JPA

- MySQL Driver

- Click Generate, download the `.zip` file, and unzip it.

- Open the project in your IDE.

Creating Models (Entities) with Hibernate


In Hibernate, a model is typically an entity class that represents a table
in the database. These classes are annotated with JPA (Java Persistence
API) annotations to map them to database tables.

Steps:

 Define a Java class that represents a database entity.


 Use annotations like @Entity, @Table, @Id, @Column, etc., to
define the mapping between the class and the database table.
 Include getter and setter methods for properties.

import javax.persistence.*;

@Entity
@Table(name = "employees")

public class Employee {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

private int id;

@Column(name = "first_name")

private String firstName;

@Column(name = "last_name")

private String lastName;

@Column(name = "email")

private String email;

public Employee() {

2. Creating Data Access Object (DAO)


A DAO (Data Access Object) is responsible for interacting with the
database. It abstracts the persistence layer and provides CRUD (Create,
Read, Update, Delete) operations for the entity.

Steps:
 Create a DAO interface for defining CRUD methods.
 Implement the DAO interface in a concrete class that uses
Hibernate to interact with the database.

public Employee(String firstName, String lastName, String email) {

this.firstName = firstName;

this.lastName = lastName;

this.email = email;

// Getters and setters

public int getId() {

return id;

public void setId(int id) {

this.id = id;

}
public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {

return lastName;

public void setLastName(String lastName) {

this.lastName = lastName;

public String getEmail() {

return email;

public void setEmail(String email) {

this.email = email;
}

2. Creating Data Access Object (DAO)


A DAO (Data Access Object) is responsible for interacting with the
database. It abstracts the persistence layer and provides CRUD (Create,
Read, Update, Delete) operations for the entity.

Steps:
 Create a DAO interface for defining CRUD methods.
 Implement the DAO interface in a concrete class that uses
Hibernate to interact with the database.

import java.util.List;

public interface EmployeeDAO {

void saveEmployee(Employee employee);

Employee getEmployee(int id);

List<Employee> getAllEmployees();
void updateEmployee(Employee employee);

void deleteEmployee(int id);

Example DAO IMPLEMENTATION:

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.query.Query;

import java.util.List;

public class EmployeeDAOImpl implements EmployeeDAO {

private SessionFactory sessionFactory;

public EmployeeDAOImpl(SessionFactory sessionFactory) {

this.sessionFactory = sessionFactory;

}
@Override

public void saveEmployee(Employee employee) {

try (Session session = sessionFactory.getCurrentSession()) {

session.beginTransaction();

session.saveOrUpdate(employee);

session.getTransaction().commit();

@Override

public Employee getEmployee(int id) {

try (Session session = sessionFactory.getCurrentSession()) {

session.beginTransaction();

Employee employee = session.get(Employee.class, id);

session.getTransaction().commit();

return employee;

}
@Override

public List<Employee> getAllEmployees() {

try (Session session = sessionFactory.getCurrentSession()) {

session.beginTransaction();

Query<Employee> query = session.createQuery("from


Employee", Employee.class);

List<Employee> employees = query.getResultList();

session.getTransaction().commit();

return employees;

@Override

public void updateEmployee(Employee employee) {

try (Session session = sessionFactory.getCurrentSession()) {

session.beginTransaction();

session.update(employee);

session.getTransaction().commit();

}
@Override

public void deleteEmployee(int id) {

try (Session session = sessionFactory.getCurrentSession()) {

session.beginTransaction();

Employee employee = session.get(Employee.class, id);

if (employee != null) {

session.delete(employee);

session.getTransaction().commit();

3. Creating Controller
In a typical Spring MVC application, the controller is responsible for
processing incoming HTTP requests and returning a response (usually a
view). In a Hibernate application, the controller interacts with the DAO
to manage data.

Steps:
 Use annotations like @Controller or @RestController to
define the controller.
 Inject the DAO or service layer.
 Handle different HTTP methods (GET, POST, PUT, DELETE) for
CRUD operations.

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller

@RequestMapping("/employees")

public class EmployeeController {

@Autowired

private EmployeeDAO employeeDAO;

@GetMapping("/list")

public String listEmployees(Model model) {

List<Employee> employees = employeeDAO.getAllEmployees();

model.addAttribute("employees", employees);

return "employee-list";
}

@GetMapping("/showFormForAdd")

public String showFormForAdd(Model model) {

Employee employee = new Employee();

model.addAttribute("employee", employee);

return "employee-form";

@PostMapping("/saveEmployee")

public String saveEmployee(@ModelAttribute("employee") Employee


employee) {

employeeDAO.saveEmployee(employee);

return "redirect:/employees/list";

@GetMapping("/showFormForUpdate")

public String showFormForUpdate(@RequestParam("employeeId")


int id, Model model) {

Employee employee = employeeDAO.getEmployee(id);


model.addAttribute("employee", employee);

return "employee-form";

@GetMapping("/delete")

public String deleteEmployee(@RequestParam("employeeId") int id)


{

employeeDAO.deleteEmployee(id);

return "redirect:/employees/list";

4. Configuring Hibernate (SessionFactory)


You need to configure Hibernate in your project by setting up a
SessionFactory object, which is responsible for creating Session
objects to interact with the database.

Steps:

 Configure Hibernate via a hibernate.cfg.xml or use Spring


Boot's application.properties.
 Create a SessionFactory bean in the configuration class (if
using Spring).
<!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.MySQLDialect</propert
y>

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

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

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

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

<!-- 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 dialect -->

<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</propert
y>

<!-- 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.Employee"/>

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

CRUD OPERATIONS :

Step 1: Set Up Maven Project

Create a Maven project in your IDE and add the following


dependencies in the pom.xml file:

<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-
java</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-
api</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
Step 2: Configure Hibernate

Create a hibernate.cfg.xml file under


the src/main/resources directory to configure Hibernate
settings:

<!DOCTYPE hibernate-configuration PUBLIC


"-//Hibernate/Hibernate Configuration
DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-
configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mys
ql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://loc
alhost:3306/hibernate_db?useSSL=false</property>
<property
name="hibernate.connection.username">root</prope
rty>
<property
name="hibernate.connection.password">root</prope
rty>
<property
name="hibernate.dialect">org.hibernate.dialect.M
ySQL8Dialect</property>
<property
name="hibernate.show_sql">true</property>
<property
name="hibernate.hbm2ddl.auto">update</property>
<mapping
class="com.example.entity.User"/>
</session-factory>
</hibernate-configuration>

Step 3: Create User Entity

Create a User entity class to represent a user in the database:

package com.example.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "user")
public class User {

@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private Long id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "email")
private String email;

// Constructors, getters, setters, and


toString() method
public User() {}
public User(String firstName, String
lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getEmail() {


return email;
}
public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
return "User [id=" + id + ", firstName="
+ firstName + ", lastName=" + lastName + ",
email=" + email + "]";
}
}

Entity Mapping Diagram

+-------------------+
| User |
+-------------------+
| id (PK) |
| first_name |
| last_name |
| email |
+-------------------+

Step 4: Create Hibernate Utility Class

Create a utility class to manage Hibernate sessions:

package com.example.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import
org.hibernate.boot.registry.StandardServiceRegis
try;
import
org.hibernate.boot.registry.StandardServiceRegis
tryBuilder;

public class HibernateUtil {


private static StandardServiceRegistry
registry;
private static SessionFactory
sessionFactory;

public static SessionFactory


getSessionFactory() {
if (sessionFactory == null) {
try {
registry = new
StandardServiceRegistryBuilder().configure().bui
ld();
MetadataSources sources = new
MetadataSources(registry);
Metadata metadata =
sources.getMetadataBuilder().build();
sessionFactory =
metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {

StandardServiceRegistryBuilder.destroy(registry)
;
}
}
}
return sessionFactory;
}

public static void shutdown() {


if (registry != null) {

StandardServiceRegistryBuilder.destroy(registry)
;
}
}
}

Step 5: Create UserDao Class for CRUD Operations

Create a UserDao class to handle CRUD operations on


the User entity:

package com.example.dao;

import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

public class UserDao {

public void saveUser(User user) {


Transaction transaction = null;
try (Session session =
HibernateUtil.getSessionFactory().openSession())
{
transaction =
session.beginTransaction();
session.save(user);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}

public List<User> getUsers() {


try (Session session =
HibernateUtil.getSessionFactory().openSession())
{
return session.createQuery("FROM
User", User.class).list();
}
}

public void updateUser(User user) {


Transaction transaction = null;
try (Session session =
HibernateUtil.getSessionFactory().openSession())
{
transaction =
session.beginTransaction();
session.update(user);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}

public void deleteUser(Long userId) {


Transaction transaction = null;
try (Session session =
HibernateUtil.getSessionFactory().openSession())
{
transaction =
session.beginTransaction();
User user = session.get(User.class,
userId);
if (user != null) {
session.delete(user);
}
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}

Step 6: Implement the Main Class

Create a main class to test the CRUD operations using


the UserDao class:

package com.example;

import com.example.dao.UserDao;
import com.example.entity.User;
import com.example.util.HibernateUtil;

import java.util.List;

public class HibernateCRUDExample {

public static void main(String[] args) {


UserDao userDao = new UserDao();

// Create
userDao.saveUser(new User("Ramesh",
"Fadatare", "[email protected]"));
userDao.saveUser(new User("Suresh",
"Kumar", "[email protected]"));

// Read
List<User> users = userDao.getUsers();
users.forEach(System.out::println);

// Update
User user = users.get(0);
user.setFirstName("Rameshwar");
userDao.updateUser(user);

// Delete
userDao.deleteUser(user.getId());

// Read
users = userDao.getUsers();
users.forEach(System.out::println);

// Shutdown Hibernate
HibernateUtil.shutdown();
}
}

1. Create User Entity: The User entity represents a table in the


database with fields id, first_name, last_name,
and email.
2. Configure Hibernate: The hibernate.cfg.xml file
configures Hibernate to connect to the MySQL database and
maps the User entity.
3. Hibernate Utility Class: The HibernateUtil class
manages the Hibernate SessionFactory and provides a
method to shut it down.
4. UserDao Class: The UserDao class contains methods for
CRUD operations
(saveUser, getUsers, updateUser, deleteUser) using
Hibernate sessions.
5. Main Class: The HibernateCRUDExample class
demonstrates how to use the UserDao class to perform
CRUD operations and displays the results.

You might also like