Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Project Implementation

The document outlines the concepts of POJOs and Beans in Java, detailing their roles in data encapsulation and Spring's IoC container. It describes a layered architecture for applications, including the presentation, controller, service, repository, and database layers, along with examples of entity classes and ORM relationships. Additionally, it provides a step-by-step guide to creating a Spring Boot project with CRUD operations using MySQL, including setting up the database, defining entities, and implementing the service and controller layers.

Uploaded by

suresh709210
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Project Implementation

The document outlines the concepts of POJOs and Beans in Java, detailing their roles in data encapsulation and Spring's IoC container. It describes a layered architecture for applications, including the presentation, controller, service, repository, and database layers, along with examples of entity classes and ORM relationships. Additionally, it provides a step-by-step guide to creating a Spring Boot project with CRUD operations using MySQL, including setting up the database, defining entities, and implementing the service and controller layers.

Uploaded by

suresh709210
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

1.

POJO and Beans Concepts:

POJO (Plain Old Java Object):

Simple Java class containing private fields, public getters/setters, and no business logic.

Facilitates easy data encapsulation and transfer between layers.

Example:

public class User {

private String name;

private int age;

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }

Beans:

Special POJOs managed by Spring's IoC (Inversion of Control) container.

Created, wired, and managed by Spring for dependency injection.

2. Layers of the Application Needed:

Presentation Layer (Frontend/UI): Handles user interaction (HTML, JSP, React, etc.).

Controller Layer: Receives requests from the UI, processes them, and sends responses (Spring
MVC Controllers).

Service Layer: Contains business logic, processes data, and communicates with the data layer.

Repository/DAO Layer: Directly interacts with the database (using JPA, Hibernate, JDBC).

Database Layer: Where data is stored (SQL, NoSQL, etc.).

Layered Architecture Example:

Client (UI) --> Controller --> Service --> Repository --> Database

3. POJO Model for the Services:

Model Classes: POJOs representing entities or DTOs (Data Transfer Objects) passed between
layers.

Example:
public class Product {

private Long id;

private String name;

private double price;

// Getters and Setters

 Use in Service Layer:

@Service

public class ProductService {

public Product getProductById(Long id) {

// Fetch from DB and return

return new Product();

4. ORM Relations Concepts:

 ORM (Object-Relational Mapping): Technique to map Java objects to database tables.

 Common Annotations (Hibernate/JPA):

o @Entity – Marks class as an entity.

o @Table – Maps class to a table.

o @Id – Primary key.

o @OneToOne, @OneToMany, @ManyToOne, @ManyToMany – Define relationships.

 Example:

@Entity

@Table(name = "orders")

public class Order {

@Id

@GeneratedValue

private Long id;

@ManyToOne
@JoinColumn(name = "user_id")

private User user;

5. Query Creation for Connection Establishment:

 SQL Queries for CRUD Operations:

 CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50));

 INSERT INTO users (id, name) VALUES (1, 'John');

 SELECT * FROM users;

 UPDATE users SET name = 'Jane' WHERE id = 1;

 DELETE FROM users WHERE id = 1;

 JPA/Hibernate Example:

 @Query("SELECT u FROM User u WHERE u.name = :name")

 List<User> findByName(@Param("name") String name);

6. Spring JDBC and Data Layers for Database Connection:

 Spring JDBC: Simplifies database interaction using JdbcTemplate.

 Configuration:

 @Configuration

 public class DatabaseConfig {

 @Bean

public DataSource dataSource() {

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost:3306/db");

dataSource.setUsername("root");

dataSource.setPassword("password");

return dataSource;

 DAO Example:
@Repository

public class UserDao {

@Autowired

private JdbcTemplate jdbcTemplate;

public List<User> getAllUsers() {

return jdbcTemplate.query("SELECT * FROM users", (rs, rowNum) ->

new User(rs.getInt("id"), rs.getString("name")));

Sunday Plan

Step 2: Create New Spring Boot Project

1. File → New → Spring Starter Project.

2. Fill in:

o Name: EmployeeServiceApp

o Type: Maven

o Java version: 11 or 17

o Packaging: Jar

o Dependencies:

 Spring Web

 Spring Data JPA

 MySQL Driver

 Lombok (optional, for reducing boilerplate code)

3. Click Finish to generate the project.

Step 3: Define Entity Classes (POJOs)

Employee Entity (Employee.java)

package com.example.employeeservice.model;
import jakarta.persistence.*;

@Entity

@Table(name = "employees")

public class Employee {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(name = "name")

private String name;

@Column(name = "department")

private String department;

@ManyToOne

@JoinColumn(name = "service_id")

private ServiceDetails serviceDetails;

// Getters and Setters

ServiceDetails Entity (ServiceDetails.java)

package com.example.employeeservice.model;

import jakarta.persistence.*;

import java.util.List;

@Entity

@Table(name = "services")

public class ServiceDetails {


@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(name = "service_name")

private String serviceName;

@OneToMany(mappedBy = "serviceDetails", cascade = CascadeType.ALL)

private List<Employee> employees;

// Getters and Setters

Step 4: Set Up ORM Relationships

 One-to-Many: ServiceDetails to Employee.

 Many-to-One: Employee to ServiceDetails.

 Use @OneToMany and @ManyToOne annotations.

Step 5: Create Database Tables

 application.properties (src/main/resources)

spring.datasource.url=jdbc:mysql://localhost:3306/employeedb

spring.datasource.username=root

spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

 MySQL Table Creation (Optional)

CREATE DATABASE employeedb;

USE employeedb;

CREATE TABLE employees (

id BIGINT AUTO_INCREMENT PRIMARY KEY,


name VARCHAR(100),

department VARCHAR(100),

service_id BIGINT,

FOREIGN KEY (service_id) REFERENCES services(id)

);

CREATE TABLE services (

id BIGINT AUTO_INCREMENT PRIMARY KEY,

service_name VARCHAR(100)

);

Step 6: Develop CRUD Operations

Employee Repository (EmployeeRepository.java)

package com.example.employeeservice.repository;

import com.example.employeeservice.model.Employee;

import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {}

Service Repository (ServiceDetailsRepository.java)

package com.example.employeeservice.repository;

import com.example.employeeservice.model.ServiceDetails;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ServiceDetailsRepository extends JpaRepository<ServiceDetails, Long> {}

Service Layer (EmployeeService.java)

package com.example.employeeservice.service;

import com.example.employeeservice.model.Employee;

import com.example.employeeservice.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class EmployeeService {

@Autowired

private EmployeeRepository employeeRepository;

public List<Employee> getAllEmployees() {

return employeeRepository.findAll();

public Employee addEmployee(Employee employee) {

return employeeRepository.save(employee);

Controller Layer (EmployeeController.java)

package com.example.employeeservice.controller;

import com.example.employeeservice.model.Employee;

import com.example.employeeservice.service.EmployeeService;

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

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

import java.util.List;

@RestController

@RequestMapping("/employees")

public class EmployeeController {


@Autowired

private EmployeeService employeeService;

@GetMapping

public List<Employee> getEmployees() {

return employeeService.getAllEmployees();

@PostMapping

public Employee addEmployee(@RequestBody Employee employee) {

return employeeService.addEmployee(employee);

Step 7: Run and Test the Application

1. Run the Spring Boot application.

2. Test using Postman or cURL:

o GET /employees – Retrieve all employees.

o POST /employees – Add a new employee (send JSON body).

3. {

4. "name": "John Doe",

5. "department": "Engineering",

6. "serviceDetails": { "id": 1 }

7. }

8. Verify the database to check if data is inserted.

Output:

 Employees with service relations are stored and retrieved from the database.
Project Running in the Eclipse

Here's a step-by-step guide to implementing this Spring Boot project using Eclipse with Maven:

Prerequisites:

 Eclipse IDE (latest version)

 Maven installed and configured

 MySQL Database (or any preferred DB)

 Java 11 or 17

 Postman for testing APIs

Step 1: Set Up Eclipse and Create a New Maven Project

1. Open Eclipse.

2. File → New → Maven Project

3. Select "Create a simple project" → Click Next.

4. Fill out:

o Group ID: com.example

o Artifact ID: employeeservice


o Name: EmployeeServiceApp

o Packaging: jar

o Java Version: 11 or 17

o Description: Employee Service Application

5. Click Finish.

Step 2: Add Spring Boot Dependencies

1. Right-click the project → Maven → Add Dependency.

2. Add the following dependencies to your pom.xml:

<dependencies>

<!-- Spring Boot Starter Web for REST APIs -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- Spring Boot Starter JPA for Database Access -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<!-- MySQL Connector -->

<dependency>

<groupId>com.mysql</groupId>

<artifactId>mysql-connector-j</artifactId>

<scope>runtime</scope>

</dependency>

<!-- Lombok to reduce boilerplate -->

<dependency>
<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

<!-- Spring Boot Starter Test -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

Step 3: Configure Application Properties

Create application.properties in src/main/resources:

spring.datasource.url=jdbc:mysql://localhost:3306/employeedb

spring.datasource.username=root

spring.datasource.password=root

spring.jpa.hibernate.ddl-auto=update

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

server.port=8080

Step 4: Create the Entity Classes

1. Employee Entity (Employee.java)

package com.example.employeeservice.model;

import jakarta.persistence.*;

import lombok.Getter;

import lombok.Setter;

@Entity
@Table(name = "employees")

@Getter

@Setter

public class Employee {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(name = "name")

private String name;

@Column(name = "department")

private String department;

@ManyToOne

@JoinColumn(name = "service_id")

private ServiceDetails serviceDetails;

2. ServiceDetails Entity (ServiceDetails.java)

package com.example.employeeservice.model;

import jakarta.persistence.*;

import lombok.Getter;

import lombok.Setter;

import java.util.List;

@Entity

@Table(name = "services")

@Getter

@Setter
public class ServiceDetails {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(name = "service_name")

private String serviceName;

@OneToMany(mappedBy = "serviceDetails", cascade = CascadeType.ALL)

private List<Employee> employees;

Step 5: Create Repositories

1. Employee Repository (EmployeeRepository.java)

package com.example.employeeservice.repository;

import com.example.employeeservice.model.Employee;

import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {}

2. ServiceDetails Repository (ServiceDetailsRepository.java)

package com.example.employeeservice.repository;

import com.example.employeeservice.model.ServiceDetails;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ServiceDetailsRepository extends JpaRepository<ServiceDetails, Long> {}

Step 6: Implement Service Layer

EmployeeService.java
package com.example.employeeservice.service;

import com.example.employeeservice.model.Employee;

import com.example.employeeservice.repository.EmployeeRepository;

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

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class EmployeeService {

@Autowired

private EmployeeRepository employeeRepository;

public List<Employee> getAllEmployees() {

return employeeRepository.findAll();

public Employee addEmployee(Employee employee) {

return employeeRepository.save(employee);

Step 7: Create Controller Layer

EmployeeController.java

package com.example.employeeservice.controller;

import com.example.employeeservice.model.Employee;

import com.example.employeeservice.service.EmployeeService;

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

import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController

@RequestMapping("/employees")

public class EmployeeController {

@Autowired

private EmployeeService employeeService;

@GetMapping

public List<Employee> getEmployees() {

return employeeService.getAllEmployees();

@PostMapping

public Employee addEmployee(@RequestBody Employee employee) {

return employeeService.addEmployee(employee);

Step 8: Create Database Tables

Run these SQL commands in your MySQL terminal:

CREATE DATABASE employeedb;

USE employeedb;

CREATE TABLE services (

id BIGINT AUTO_INCREMENT PRIMARY KEY,

service_name VARCHAR(100)

);
CREATE TABLE employees (

id BIGINT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

department VARCHAR(100),

service_id BIGINT,

FOREIGN KEY (service_id) REFERENCES services(id)

);

Step 9: Run the Application

1. Right-click the project → Run As → Spring Boot App.

2. The app will start on http://localhost:8080.

3. Use Postman or cURL to test:

 GET /employees – Retrieve all employees

 POST /employees – Add new employee

"name": "John Doe",

"department": "Engineering",

"serviceDetails": { "id": 1 }

Step 10: Verify the Data in Database

Run:

SELECT * FROM employees;

Your employee records should appear.

You might also like