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

Rest-Lab programs

The document provides a comprehensive overview of a Spring Boot application with various controllers and services for managing different entities such as patients, products, employees, and children. Each section includes code snippets demonstrating RESTful API endpoints for retrieving, creating, updating, and deleting records, along with the necessary model and repository classes. Key features include the use of annotations like @RestController, @GetMapping, @PostMapping, and @Value for configuration management.

Uploaded by

vigncs150
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 views99 pages

Rest-Lab programs

The document provides a comprehensive overview of a Spring Boot application with various controllers and services for managing different entities such as patients, products, employees, and children. Each section includes code snippets demonstrating RESTful API endpoints for retrieving, creating, updating, and deleting records, along with the necessary model and repository classes. Key features include the use of annotations like @RestController, @GetMapping, @PostMapping, and @Value for configuration management.

Uploaded by

vigncs150
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/ 99

Ex-1 To Retrieve Welcome message

package com.example.springapp.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController{
@GetMapping("/welcome")
public String welcome()
{
return "Welcome Spring Boot!";
}
}

Output:
Ex.2 To retrieve a color choice using @Value

package com.example.springapp.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@GetMapping("/favouriteColor")
public String Color(@RequestParam String color)
{
return "My favorite color is "+color+"!";
}
}

Output
Ex.3 To display application information using @Value
ApiController.java

package com.examly.springapp.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.examly.springapp.config.AppConfig;
@RestController
public class ApiController {
private AppConfig appconfig;

public ApiController(AppConfig appconfig) {


this.appconfig = appconfig;
}

@GetMapping("/info")
public String getApp()
{
return "App Name:" + appconfig.getAppName() + ",Version:" +
appconfig.getAppVersion();
}
}
AppConfig.java
package com.examly.springapp.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AppConfig {
@Value("${app.name}")
private String appName;
@Value("${app.version}")
private String appVersion;
public AppConfig()
{

}
public AppConfig(String appName, String appVersion) {
this.appName = appName;
this.appVersion = appVersion;
}
public String getAppName() {
return appName;
}
public String getAppVersion() {
return appVersion;
}
public void setAppName(String appName) {
this.appName = appName;
}
public void setAppVersion(String appVersion) {
this.appVersion = appVersion;
}

}
Ex-4 To retrieve student details using @JsonIgnore
StudentControler.java
package com.examly.springapp.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.examly.springapp.model.Student;
@RestController
public class StudentController {
@GetMapping("/student")
public Student getStu()
{
Student stuobj=new Student(1L,"John Doe","This is a student description");
return stuobj;
}
}
Student.java
package com.examly.springapp.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Student {
private long id;
private String name;
@JsonIgnore
private String description;

public Student()
{

}
public Student(long id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public void setId(long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
}
Ex-5 Managing Patient details using POST and GET operations

Patient.java
package com.example.springapp.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Patient {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int patientId;
private String patientName;
private String doctorName;
private String disease;
private String medication;
public Patient()
{
}
public Patient(int patientId, String patientName, String doctorName, String disease, String
medication) {
this.patientId = patientId;
this.patientName = patientName;
this.doctorName = doctorName;
this.disease = disease;
this.medication = medication;
}
public int getPatientId() {
return patientId;
}
public String getPatientName() {
return patientName;
}
public String getDoctorName() {
return doctorName;
}
public String getDisease() {
return disease;
}
public String getMedication() {
return medication;
}
public void setPatientId(int patientId) {
this.patientId = patientId;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public void setDoctorName(String doctorName) {
this.doctorName = doctorName;
}
public void setDisease(String disease) {
this.disease = disease;
}
public void setMedication(String medication) {
this.medication = medication;
}

PatientController.java
package com.example.springapp.controller;

import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.springapp.model.Patient;
import com.example.springapp.service.PatientService;

@RestController
@RequestMapping("/api")
public class PatientController {
private PatientService patientService;
@Autowired
public PatientController(PatientService patientService) {
this.patientService = patientService;
}

@PostMapping("/patient")
public ResponseEntity<Patient> postPatient(@RequestBody Patient obj)
{
Patient pobj=patientService.postPatient(obj);
return ResponseEntity.status(HttpStatus.CREATED).body(pobj);
}
@GetMapping("/patient")
public ResponseEntity<List<Patient>> getAllpatients()
{
List <Patient> patients=patientService.getAllpatients();
return new ResponseEntity<>(patients,HttpStatus.OK);
}
@GetMapping("/patient/{patientId}")
public ResponseEntity<Patient> getPatientById(@PathVariable int patientId)
{
Optional<Patient> patient=patientService.getPatientById(patientId);
if(patient.isPresent())
{
return new ResponseEntity<Patient>(patient.get(),HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

PatientService.java
package com.example.springapp.service;

import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Service;

import com.example.springapp.model.Patient;
import com.example.springapp.repository.PatientRepo;

@Service
public class PatientService {
PatientRepo patientRepo;

public PatientService(PatientRepo patientRepo) {


this.patientRepo = patientRepo;
}
public Patient postPatient(Patient obj)
{
return patientRepo.save(obj);
}
public List<Patient> getAllpatients()
{
return patientRepo.findAll();
}
public Optional<Patient> getPatientById(Integer patientId)
{
return patientRepo.findById(patientId);
}
}

PatientRepo.java
package com.example.springapp.repository;

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

import com.example.springapp.model.Patient;
@Repository
public interface PatientRepo extends JpaRepository<Patient, Integer> {

}
Ex-6 Managing Product details with POST and GET operations
Product.java
package com.example.springapp.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int productId;
private String productName;
private double price;
private String description;
private int quantity;

public Product(){

public Product(int productId, String productName, double price, String description, int
quantity) {
this.productId = productId;
this.productName = productName;
this.price = price;
this.description = description;
this.quantity = quantity;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = 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;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
ProductController.java
package com.example.springapp.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springapp.model.Product;
import com.example.springapp.service.ProductService;

@RestController
@RequestMapping("/api")
public class ProductController {
@Autowired
private ProductService productService;

public ProductController(ProductService productService) {


this.productService = productService;
}

@PostMapping("/product/add")
public ResponseEntity <Product> postProduct(@RequestBody Product obj)
{
Product pobj=productService.postProduct(obj);
return ResponseEntity.status(HttpStatus.CREATED).body(pobj);
}
@GetMapping("/product")
public ResponseEntity<List<Product>> getAllProducts()
{
List<Product> lobj =productService.getAllProducts();
return new ResponseEntity<>(lobj,HttpStatus.OK);
}
@GetMapping("/product/{productId}")
public ResponseEntity<Product> getByProductId(@PathVariable int productid)
{
Optional<Product> product=productService.getProductById(productid);
if (product.isPresent())
{
return new ResponseEntity<Product>(product.get(),HttpStatus.OK);

}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

}
ProductService.java
package com.example.springapp.service;

import java.util.List;
import java.util.Optional;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import com.example.springapp.model.Product;
import com.example.springapp.repository.ProductRepo;

@Service
public class ProductService {
private ProductRepo productRepo;
public ProductService(ProductRepo productRepo) {
this.productRepo = productRepo;
}

public Product postProduct(@NonNull Product obj)


{

return productRepo.save(obj);

}
public List<Product> getAllProducts()
{
return productRepo.findAll();
}
public Optional<Product> getProductById(@NonNull Integer productid)
{
return productRepo.findById(productid);
}
}

ProductRepo.java
package com.example.springapp.repository;

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

import com.example.springapp.model.Product;

@Repository
public interface ProductRepo extends JpaRepository<Product,Integer>{

}
Ex-7 Managing Employee Details with GET,POST and DELETE Operations

Employee.java

package com.example.springapp.model;

import javax.persistence.Entity;

import javax.persistence.Id;

@Entity

public class Employee {

@Id

private int employeeId;

private String employeeName;

private String employeeEmail;

private double salary;

private String department;

public Employee()

public Employee(int employeeId, String employeeName, String employeeEmail, double


salary, String department) {

this.employeeId = employeeId;

this.employeeName = employeeName;

this.employeeEmail = employeeEmail;
this.salary = salary;

this.department = department;

public int getEmployeeId() {

return employeeId;

public void setEmployeeId(int employeeId) {

this.employeeId = employeeId;

public String getEmployeeName() {

return employeeName;

public void setEmployeeName(String employeeName) {

this.employeeName = employeeName;

public String getEmployeeEmail() {

return employeeEmail;

public void setEmployeeEmail(String employeeEmail) {

this.employeeEmail = employeeEmail;

}
public double getSalary() {

return salary;

public void setSalary(double salary) {

this.salary = salary;

public String getDepartment() {

return department;

public void setDepartment(String department) {

this.department = department;

EmployeeController.java

package com.example.springapp.controller;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

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

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

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

import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

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

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

import com.example.springapp.model.Employee;

import com.example.springapp.service.EmployeeService;

@RestController

@RequestMapping("/api")

public class EmployeeController {

private EmployeeService employeeService;

public EmployeeController(EmployeeService employeeService) {

this.employeeService = employeeService;

@PostMapping("/employee")

public ResponseEntity<Employee> addEmployee(Employee e)

Employee obj=employeeService.addEmployee(e);

return new ResponseEntity<>(obj,HttpStatus.CREATED);

@PutMapping("/employee/{employeeId}")

public ResponseEntity<Employee> updateEmployee(@PathVariable int employeeId,


@RequestBody Employee e)
{

if (employeeService.updateEmployee(employeeId,e)==true) {

return new ResponseEntity<>(e,HttpStatus.OK);

return new ResponseEntity<>(HttpStatus.NOT_FOUND);

@DeleteMapping("/employee/{employeeId}")

public ResponseEntity<Boolean> deleteEmployeeById(@PathVariable int employeeId)

if (employeeService.deleteEmployeeById(employeeId)==true) {

return new ResponseEntity<>(true,HttpStatus.OK);

return new ResponseEntity<>(false,HttpStatus.NOT_FOUND);

EmployeeService.java

package com.example.springapp.service;

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

import org.springframework.stereotype.Service;

import com.example.springapp.model.Employee;

import com.example.springapp.repository.EmployeeRepo;
@Service

public class EmployeeService {

private EmployeeRepo employeeRepo;

@Autowired

public EmployeeService(EmployeeRepo employeeRepo) {

this.employeeRepo = employeeRepo;

public Employee addEmployee(Employee e)

return employeeRepo.save(e);

public boolean updateEmployee(int employeeId, Employee e)

if (employeeRepo.findById(employeeId)!=null) {

employeeRepo.save(e);

return true;

return false;

public boolean deleteEmployeeById(int employeeId)

{
if (employeeRepo.findById(employeeId)==null) {

return false;

else{

employeeRepo.deleteById(employeeId);

return true;

EmployeeRepo.java

package com.example.springapp.repository;

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

import org.springframework.stereotype.Repository;

import com.example.springapp.model.Employee;

@Repository

public interface EmployeeRepo extends JpaRepository<Employee, Integer> {

}
Ex-8 Managing Children details using POST and GET operations with
Pagination and Sorting
Children.java

package com.example.springapp.model;

import javax.persistence.Entity;

import javax.persistence.Id;

@Entity

public class Children {

@Id

int babyId;

String babyFirstName,babyLastName,fatherName,motherName,address;

public Children() {

public Children(int babyId, String babyFirstName, String babyLastName, String


fatherName, String motherName,

String address) {

this.babyId = babyId;

this.babyFirstName = babyFirstName;

this.babyLastName = babyLastName;

this.fatherName = fatherName;

this.motherName = motherName;

this.address = address;
}

public int getBabyId() {

return babyId;

public void setBabyId(int babyId) {

this.babyId = babyId;

public String getBabyFirstName() {

return babyFirstName;

public void setBabyFirstName(String babyFirstName) {

this.babyFirstName = babyFirstName;

public String getBabyLastName() {

return babyLastName;

public void setBabyLastName(String babyLastName) {

this.babyLastName = babyLastName;

public String getFatherName() {

return fatherName;
}

public void setFatherName(String fatherName) {

this.fatherName = fatherName;

public String getMotherName() {

return motherName;

public void setMotherName(String motherName) {

this.motherName = motherName;

public String getAddress() {

return address;

public void setAddress(String address) {

this.address = address;

Children_Controller

package com.example.springapp.controller;

import java.util.List;

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

import org.springframework.http.ResponseEntity;

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

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

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

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

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

import com.example.springapp.model.Children;

import com.example.springapp.service.ChildrenService;

@RestController

public class ChildrenController {

@Autowired

ChildrenService cs;

//post

@PostMapping("/api/children")

public ResponseEntity<Children> create(@RequestBody Children c)

Children obj = cs.create(c);

return new ResponseEntity<>(obj,HttpStatus.CREATED);

//sorting
@GetMapping("/api/children/sortBy/{field}")

public List<Children> g(@PathVariable String field)

return cs.sort(field);

//pagination

@GetMapping("/api/children/{offset}/{pagesize}")

public List<Children> get(@PathVariable int offset,@PathVariable int pagesize)

return cs.page(pagesize, offset);

//sorting and pagination

@GetMapping("/api/children/{offset}/{pagesize}/{field}")

public List<Children> getsorting(@PathVariable int offset,@PathVariable int


pagesize,@PathVariable String field)

return cs.getsort(offset,pagesize,field);

Children_Service

package com.example.springapp.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Pageable;

import org.springframework.data.domain.Sort;

import org.springframework.stereotype.Service;

import com.example.springapp.model.Children;

import com.example.springapp.repository.ChildrenRepo;

@Service

public class ChildrenService {

@Autowired

ChildrenRepo cr;

//post

public Children create(Children c)

return cr.save(c);

//sorting by field

public List<Children> sort(String field)

Sort sort=Sort.by(Sort.Direction.ASC,field);

return cr.findAll(sort);
}

//pagination

public List<Children> page(int pageSize,int pageNumber)

Pageable page=PageRequest.of(pageNumber, pageSize);

return cr.findAll(page).getContent();

//sorting and pagination

public List<Children> getsort(int pageNumber,int pageSize,String field)

return cr.findAll(PageRequest.of(pageNumber, pageSize)

.withSort(Sort.by(Sort.Direction.ASC,field))).getContent();

Children_Repository

package com.example.springapp.repository;

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

import com.example.springapp.model.Children;

public interface ChildrenRepo extends JpaRepository<Children,Integer>{

}
Ex-9 Managing Person details using JPA
Person_Model

package com.example.springapp.model;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

@Entity

public class Person {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private int personId;

private String firstName;

private String lastName;

private int age;

private String gender;

public Person() {

public Person(int personId, String firstName, String lastName, int age, String gender) {

this.personId = personId;

this.firstName = firstName;
this.lastName = lastName;

this.age = age;

this.gender = gender;

public int getPersonId() {

return personId;

public void setPersonId(int personId) {

this.personId = personId;

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 int getAge() {

return age;

public void setAge(int age) {

this.age = age;

public String getGender() {

return gender;

public void setGender(String gender) {

this.gender = gender;

Person_Controller

package com.example.springapp.controller;

import java.util.List;

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

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

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

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

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

import com.example.springapp.model.Person;

import com.example.springapp.service.PersonService;

@RestController

public class PersonController {

@Autowired

private PersonService service;

@PostMapping("/api/person")

public ResponseEntity<?> addPerson(@RequestBody Person person){

try {

return new ResponseEntity<>(service.addPerson(person),HttpStatus.CREATED);

} catch (Exception e) {

return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

@GetMapping("/api/person")

public ResponseEntity<?>getPerson(){
try {

return new ResponseEntity<>(service.getPerson(),HttpStatus.OK);

} catch (Exception e) {

return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

@GetMapping("/api/person/byAge")

public ResponseEntity<?>sort(@RequestParam String age){

try {

return new ResponseEntity<>(service.sort(age),HttpStatus.OK);

} catch (Exception e) {

return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

Person_Service

package com.example.springapp.service;

import java.util.List;

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

import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.example.springapp.model.Person;

import com.example.springapp.repository.PersonRepo;

@Service

public class PersonService {

@Autowired

private PersonRepo repo;

public Person addPerson(Person person) {

return repo.save(person);

public List<Person> getPerson() {

return repo.findAll();

public List <Person> sort(String age) {

Sort sort = Sort.by(Sort.Direction.ASC,"age");

return repo.findAll(sort);

Person_Repository

package com.example.springapp.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.springapp.model.Person;

public interface PersonRepo extends JpaRepository<Person,Integer>{

}
Ex-10 Managing Person details using JPQL-specific search patterns

Person.java

package com.examly.springapp.model;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

@Entity

public class Person {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private long id;

private String name;

private int age;

public Person()

public Person(long id, String name, int age) {

this.id = id;

this.name = name;

this.age = age;
}

public long getId() {

return id;

public void setId(long id) {

this.id = id;

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;

PersonController.java
package com.examly.springapp.controller;

import java.util.List;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

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

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

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

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

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

import com.examly.springapp.model.Person;

import com.examly.springapp.service.PersonService;

@RestController

public class PersonController {

private PersonService personService;

public PersonController(PersonService personService) {

this.personService = personService;

@PostMapping("/person")

public ResponseEntity<Person> addPerson(@RequestBody Person p)

return new ResponseEntity<>(personService.addPerson(p),HttpStatus.CREATED);


}

@GetMapping("/person/startsWithName/{value}")

public ResponseEntity<List<Person>> getPersonStartingName(@PathVariable String


value)

return new
ResponseEntity<>(personService.getPersonStartingName(value),HttpStatus.OK);

@GetMapping("/person/endsWithName/{value}")

public ResponseEntity<List<Person>> getPersonEndingName(@PathVariable String


value)

return new
ResponseEntity<>(personService.getPersonEndingName(value),HttpStatus.OK);

PersonRepo.java

package com.examly.springapp.repository;

import java.util.List;

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

import org.springframework.stereotype.Repository;

import com.examly.springapp.model.Person;

@Repository
public interface PersonRepo extends JpaRepository<Person,Long>{

List<Person> findByNameStartsWith(String value);

List<Person> findByNameEndsWith(String value);

PersonService.java

package com.examly.springapp.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.examly.springapp.model.Person;

import com.examly.springapp.repository.PersonRepo;

@Service

public class PersonService {

private PersonRepo personRepo;

public PersonService(PersonRepo personRepo) {

this.personRepo = personRepo;

public Person addPerson(Person p)

return personRepo.save(p);

public List<Person> getPersonStartingName(String value)


{

return personRepo.findByNameStartsWith(value);

public List<Person> getPersonEndingName(String value)

return personRepo.findByNameEndsWith(value);

}
Ex-11 Managing Person details using custom JPQL queries

package com.example.springapp.model;

import javax.persistence.Entity;

import javax.persistence.Id;

@Entity

public class Person {

@Id

private int personId;

private String firstName,lastName,gender,email;

private int age;

public Person() {

public Person(int personId, String firstName, String lastName, String gender, String
email, int age) {

this.personId = personId;

this.firstName = firstName;

this.lastName = lastName;

this.gender = gender;

this.email = email;

this.age = age;

}
public int getPersonId() {

return personId;

public void setPersonId(int personId) {

this.personId = personId;

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 getGender() {

return gender;

}
public void setGender(String gender) {

this.gender = gender;

public String getEmail() {

return email;

public void setEmail(String email) {

this.email = email;

public int getAge() {

return age;

public void setAge(int age) {

this.age = age;

PersonController.java

package com.example.springapp.controller;

import java.util.List;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;

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

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

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

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

import com.example.springapp.model.Person;

import com.example.springapp.service.PersonService;

@RestController

public class PersonController {

private PersonService personService;

public PersonController(PersonService personService) {

this.personService = personService;

@PostMapping("/api/person")

public ResponseEntity<Person> addPerson(@RequestBody Person p)

return new ResponseEntity<>(personService.addPerson(p),HttpStatus.CREATED);

@GetMapping("/api/person/byage/{age}")

public ResponseEntity<List<Person>> getPersonByAge(@PathVariable int age)


{

return new ResponseEntity<>(personService.getPersonByAge(age),HttpStatus.OK);

PersonService.java

package com.example.springapp.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.example.springapp.model.Person;

import com.example.springapp.repository.PersonRepo;

@Service

public class PersonService {

private PersonRepo personRepo;

public PersonService(PersonRepo personRepo) {

this.personRepo = personRepo;

public Person addPerson(Person p)

return personRepo.save(p);

public List<Person> getPersonByAge(int age)


{

return personRepo.findPersonByAge(age);

PerosnRepo.java

package com.example.springapp.repository;

import java.util.List;

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

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

import org.springframework.stereotype.Repository;

import com.example.springapp.model.Person;

@Repository

public interface PersonRepo extends JpaRepository<Person,Integer>{

@Query("select p from Person p where p.age=?1")

public List<Person> findPersonByAge(int age);

}
Ex-12 Managing Person details using Spring JPA with
one-to-one mapping with Address Entity

Address.java

package com.examly.springapp.model;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.OneToOne;

import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity

public class Address {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String street;

private String city;

private String zipCode;

public Person getPerson() {

return person;

}
public void setPerson(Person person) {

this.person = person;

@OneToOne

@JsonBackReference

private Person person;

public Address()

public Address(Long id, String street, String city, String zipCode) {

this.id = id;

this.street = street;

this.city = city;

this.zipCode = zipCode;

public Long getId() {

return id;

public void setId(Long id) {

this.id = id;

}
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 getZipCode() {

return zipCode;

public void setZipCode(String zipCode) {

this.zipCode = zipCode;

Person.java

package com.examly.springapp.model;
import javax.persistence.CascadeType;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.OneToOne;

import com.fasterxml.jackson.annotation.JsonManagedReference;

@Entity

public class Person {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;

private String email;

private String phoneNumber;

private String nationality;

@OneToOne(mappedBy = "person",cascade = CascadeType.ALL)

@JsonManagedReference

private Address address;

public Person()

{
}

public Person(Long id, String name, String email, String phoneNumber, String
nationality, Address address) {

this.id = id;

this.name = name;

this.email = email;

this.phoneNumber = phoneNumber;

this.nationality = nationality;

this.address = address;

public Long getId() {

return id;

public void setId(Long 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;

public String getPhoneNumber() {

return phoneNumber;

public void setPhoneNumber(String phoneNumber) {

this.phoneNumber = phoneNumber;

public String getNationality() {

return nationality;

public void setNationality(String nationality) {

this.nationality = nationality;

public Address getAddress() {

return address;

}
public void setAddress(Address address) {

this.address = address;

AddressController.java

package com.examly.springapp.controller;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

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

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

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

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

import com.examly.springapp.model.Address;

import com.examly.springapp.model.Person;

import com.examly.springapp.service.AddressService;

import com.examly.springapp.service.PersonService;

@RestController

public class AddressController {

private AddressService addressService;

private PersonService personService;

public AddressController(AddressService addressService, PersonService personService)


{
this.addressService = addressService;

this.personService = personService;

@PostMapping("address/person/{personId}")

public ResponseEntity<Address> postAddress(@RequestBody Address aobj,


@PathVariable("personId") Long id)

Person pobj=personService.getPersonById(id).orElse(null);

aobj.setPerson(pobj);

addressService.postAddress(aobj);

return new ResponseEntity<Address>(aobj,HttpStatus.CREATED);

PersonController

package com.examly.springapp.controller;

import java.util.List;

import java.util.Optional;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

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

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

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

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

import com.examly.springapp.model.Person;

import com.examly.springapp.service.PersonService;

@RestController

public class PersonController {

private PersonService personService;

public PersonController(PersonService personService) {

this.personService = personService;

@PostMapping("/person")

public ResponseEntity<Person> postPerson(@RequestBody Person obj)

Person pobj=personService.postPerson(obj);

return new ResponseEntity<Person>(pobj,HttpStatus.CREATED);

@GetMapping("/person")

public ResponseEntity<List<Person>> getPersons()

List<Person> pobj=personService.getPersons();

return new ResponseEntity<List<Person>>(pobj,HttpStatus.OK);


}

@GetMapping("/person/{personId}")

public ResponseEntity<Person> getPersonById(@PathVariable("personId") Long id)

Optional<Person> pobj=personService.getPersonById(id);

return new ResponseEntity<>(pobj.get(),HttpStatus.OK);

PersonRepository

package com.examly.springapp.repository;

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

import org.springframework.stereotype.Repository;

import com.examly.springapp.model.Person;

@Repository

public interface PersonRepository extends JpaRepository<Person,Long> {

AddressRepository

package com.examly.springapp.repository;

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

import org.springframework.stereotype.Repository;
import com.examly.springapp.model.Address;

@Repository

public interface AddressRepository extends JpaRepository<Address,Long> {

PersonService

package com.examly.springapp.service;

import java.util.List;

import java.util.Optional;

import org.springframework.stereotype.Service;

import com.examly.springapp.model.Person;

import com.examly.springapp.repository.PersonRepository;

@Service

public class PersonService {

private PersonRepository personRepo;

public PersonService(PersonRepository personRepo) {

this.personRepo = personRepo;

public Person postPerson(Person obj)

return personRepo.save(obj);
}

public List<Person> getPersons()

return personRepo.findAll();

public Optional<Person> getPersonById(Long id)

return personRepo.findById(id);

AddressService.java

package com.examly.springapp.service;

import org.springframework.stereotype.Service;

import com.examly.springapp.model.Address;

import com.examly.springapp.repository.AddressRepository;

@Service

public class AddressService {

private AddressRepository addressRepo;

public AddressService(AddressRepository addressRepo) {

this.addressRepo = addressRepo;

}
public Address postAddress(Address aobj)

return addressRepo.save(aobj);

}
Ex-13 Managing Author and Book details using Spring JPA with
one-to-many mapping
Author.java
package com.examly.springapp.model;

import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import com.fasterxml.jackson.annotation.JsonManagedReference;

@Entity
public class Author {
@Id
private int id;
private String name;
private String email;
private String phoneNumber;
private String address;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
@JsonManagedReference
private List<Book> books;

public Author()
{

public Author(int id, String name, String email, String phoneNumber, String address,
List<Book> books) {
this.id = id;
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
this.address = address;
this.books = books;
}

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;
}

public String getPhoneNumber() {


return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {


this.phoneNumber = phoneNumber;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

public List<Book> getBooks() {


return books;
}

public void setBooks(List<Book> books) {


this.books = books;
}
}

Book.java
package com.examly.springapp.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity
public class Book {
@Id
//@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;
private String genre;
private int publicationYear;
private String isbn;
private double price;
@ManyToOne
@JoinColumn(name = "authorId")
@JsonBackReference
private Author author;

public Book()
{

public Book(int id, String title, String genre, int publicationYear, String isbn, double
price, Author author) {
this.id = id;
this.title = title;
this.genre = genre;
this.publicationYear = publicationYear;
this.isbn = isbn;
this.price = price;
this.author = author;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getGenre() {


return genre;
}

public void setGenre(String genre) {


this.genre = genre;
}

public int getPublicationYear() {


return publicationYear;
}

public void setPublicationYear(int publicationYear) {


this.publicationYear = publicationYear;
}

public String getIsbn() {


return isbn;
}

public void setIsbn(String isbn) {


this.isbn = isbn;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

public Author getAuthor() {


return author;
}

public void setAuthor(Author author) {


this.author = author;
}

AuthorController.java
package com.examly.springapp.controller;

import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.examly.springapp.model.Author;
import com.examly.springapp.service.AuthorService;

@RestController
public class AuthorController {
private AuthorService authorService;

public AuthorController(AuthorService authorService) {


this.authorService = authorService;
}
@PostMapping("/author")
public ResponseEntity<Author> postAuthor(@RequestBody Author obj)
{
Author aobj=authorService.postAuthor(obj);
if(aobj!=null)
return new ResponseEntity<>(aobj,HttpStatus.CREATED);
else
return new ResponseEntity<>(aobj,HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/author/{authorId}")
public ResponseEntity<Author> getAuthorById(@PathVariable("authorId") int
authorId)
{
Author aobj=authorService.getAuthorById(authorId);
if (aobj!=null) {
return new ResponseEntity<> (aobj,HttpStatus.OK);
}
return new ResponseEntity<>(aobj,HttpStatus.NOT_FOUND);
}
@GetMapping("/author")
public ResponseEntity<List<Author>> getAuthors()
{
//List<Author> lobj=authorService.getAuthors();
return new ResponseEntity<>(authorService.getAuthors(),HttpStatus.OK);
}
@PutMapping("/author/{authorId}")
public ResponseEntity<Author> putAuthor(@PathVariable("authorId") int
authorId,@RequestBody Author aobj)
{
Author obj=authorService.putAuthor(authorId,aobj);
if(obj!=null)
return new ResponseEntity<>(obj,HttpStatus.OK);
else
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
}

BookController.java
package com.examly.springapp.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.examly.springapp.model.Author;
import com.examly.springapp.model.Book;
import com.examly.springapp.service.AuthorService;
import com.examly.springapp.service.BookService;

@RestController
public class BookController {

private BookService bookService;


private AuthorService authorService;

public BookController(BookService bookService, AuthorService authorService) {


this.bookService = bookService;
this.authorService = authorService;
}

@PostMapping("book/author/{authorId}")
public ResponseEntity<Book>postBook( @PathVariable("authorId") int
authorId,@RequestBody Book b )
{
Author aobj=authorService.getAuthorById(authorId);
b.setAuthor(aobj);
return new ResponseEntity<Book>(bookService.postBook(b),HttpStatus.CREATED);
}
@DeleteMapping("book/{bookId}")
public ResponseEntity<?> deleteBookById(@PathVariable int bookId)
{
boolean deleted=bookService.deleteBookById(bookId);
if(deleted)
return ResponseEntity.ok("Book deleted successfully");
else
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Book not found with
ID:" + bookId);

}
}

AuthorRepo.java
package com.examly.springapp.repository;

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

import com.examly.springapp.model.Author;
@Repository
public interface AuthorRepository extends JpaRepository<Author,Integer>{

BookRepo.java
package com.examly.springapp.repository;

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

import com.examly.springapp.model.Book;

@Repository
public interface BookRepository extends JpaRepository<Book,Integer> {

AuthorService.java
package com.examly.springapp.service;

import java.util.List;
import org.springframework.stereotype.Service;
import com.examly.springapp.model.Author;
import com.examly.springapp.repository.AuthorRepository;

@Service
public class AuthorService {
private AuthorRepository authorRepo;

public AuthorService(AuthorRepository authorRepo) {


this.authorRepo = authorRepo;
}
public Author postAuthor(Author obj)
{

return authorRepo.save(obj);
}
public Author getAuthorById(int id)
{
return authorRepo.findById(id).orElse(null);
}
public List<Author> getAuthors()
{
return authorRepo.findAll();
}
public Author putAuthor(int authorId,Author aobj)
{
Author obj=authorRepo.findById(authorId).orElse(null);
if (obj!=null) {
obj.setAddress(aobj.getAddress());
obj.setEmail(aobj.getEmail());
obj.setPhoneNumber(aobj.getPhoneNumber());
return authorRepo.save(aobj);
}
return authorRepo.save(aobj);
}
}

BookService.java
package com.examly.springapp.service;

import org.springframework.stereotype.Service;
import com.examly.springapp.model.Book;
import com.examly.springapp.repository.BookRepository;

@Service
public class BookService {
private BookRepository bookRepo;

public BookService(BookRepository bookRepo) {


this.bookRepo = bookRepo;
}

public Book postBook(Book book)


{
return bookRepo.save(book);
}
public Book getBookById(int id)
{
return bookRepo.findById(id).orElse(null);
}
public Boolean deleteBookById(int bookId)
{
if(this.getBookById(bookId)==null)
return false;
bookRepo.deleteById(bookId);
return true;
} }
Ex-14 Managing Employee and Address details using
Spring JPA with one-one mapping using Criteria API

Address.java

package com.examly.springapp.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String city,street;
@OneToOne
@JsonBackReference
private Employee employee;
public Address()
{

public Address(int id, String city, String street, Employee employee) {


this.id = id;
this.city = city;
this.street = street;
this.employee = employee;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getStreet() {


return street;
}

public void setStreet(String street) {


this.street = street;
}

public Employee getEmployee() {


return employee;
}

public void setEmployee(Employee employee) {


this.employee = employee;
}

Employee.java
package com.examly.springapp.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;

import com.fasterxml.jackson.annotation.JsonManagedReference;

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToOne(mappedBy = "employee",cascade = CascadeType.ALL)
@JsonManagedReference
private Address address;

public Employee()
{

public Employee(int id, String name, Address address) {


this.id = id;
this.name = name;
this.address = address;
}

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 Address getAddress() {


return address;
}

public void setAddress(Address address) {


this.address = address;
}
}

AddressController.java
package com.examly.springapp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.examly.springapp.model.Address;
import com.examly.springapp.model.Employee;
import com.examly.springapp.service.AddressService;
import com.examly.springapp.service.EmployeeService;

@RestController
public class AddressController {
private AddressService addService;
@Autowired
private EmployeeService empService;
public AddressController(AddressService addService) {
this.addService = addService;
}
@PostMapping("/address/employee/{id}")
public ResponseEntity<Address> addAddress(@RequestBody Address a,@PathVariable
int id)
{
Employee eobj=empService.getEmployeeById(id);
a.setEmployee(eobj);
return new ResponseEntity<>(addService.addAddress(a),HttpStatus.CREATED);
}
}

EmployeeController.java
package com.examly.springapp.controller;

import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.examly.springapp.model.Employee;
import com.examly.springapp.service.EmployeeService;

@RestController
public class EmployeeController {
private EmployeeService empService;

public EmployeeController(EmployeeService empService) {


this.empService = empService;
}
@PostMapping("/employee")
public ResponseEntity<Employee> addEmployee(@RequestBody Employee e)
{
return new ResponseEntity<>(empService.addEmployee(e),HttpStatus.CREATED);
}
@GetMapping("/employees-inner-join")
public ResponseEntity<List<Employee>> getAllEmployeesByInnerJoin()
{
return new
ResponseEntity<>(empService.getAllEmployeesByInnerJoin(),HttpStatus.OK);
}
@GetMapping("/employees-left-outer-join")
public ResponseEntity<List<Employee>> getAllEmployeesWithLeftOuterjoin()
{
return new
ResponseEntity<>(empService.getAllEmployeesWithLeftOuterjoin(),HttpStatus.OK);
}
}

AddressRepo.java
package com.examly.springapp.repository;

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

import com.examly.springapp.model.Address;

@Repository
public interface AddressRepository extends JpaRepository<Address,Integer> {
}

EmployeeRepo.java
package com.examly.springapp.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.examly.springapp.model.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Integer>{
@Query("select e from Employee e inner join e.address a")
List<Employee> findAllEmployeesWithInnerJoin();
@Query("select e from Employee e left outer join e.address a")
List<Employee> findAllEmployeesWithLeftOuterJoin();
}

AddressService.java
package com.examly.springapp.service;

import org.springframework.stereotype.Service;

import com.examly.springapp.model.Address;
import com.examly.springapp.repository.AddressRepository;

@Service
public class AddressService {
private AddressRepository addRepo;

public AddressService(AddressRepository addRepo) {


this.addRepo = addRepo;
}
public Address addAddress(Address a)
{
return addRepo.save(a);
}

EmployeeService.java
package com.examly.springapp.service;
import java.util.List;

import org.springframework.stereotype.Service;

import com.examly.springapp.model.Employee;
import com.examly.springapp.repository.EmployeeRepository;

@Service
public class EmployeeService {
private EmployeeRepository empRepo;

public EmployeeService(EmployeeRepository empRepo) {


this.empRepo = empRepo;
}
public Employee addEmployee(Employee e)
{
return empRepo.save(e);
}
public Employee getEmployeeById(int id)
{
return empRepo.findById(id).orElse(null);
}
public List<Employee> getAllEmployeesByInnerJoin()
{
return empRepo.findAllEmployeesWithInnerJoin();
}
public List<Employee> getAllEmployeesWithLeftOuterjoin()
{
return empRepo.findAllEmployeesWithLeftOuterJoin();
}
}
Ex-15 Managing Employee and Payroll details using JPA with
one-to-one mapping with Swagger API

package com.examly.springapp.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api()
{
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.examly.springapp.controller"))
.paths(PathSelectors.any())
.build();
}
}

package com.examly.springapp.controller;

import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.examly.springapp.model.Employee;
import com.examly.springapp.model.Payroll;
import com.examly.springapp.service.EmployeeService;

@RestController
public class EmployeeController {
private EmployeeService employeeService;

public EmployeeController(EmployeeService employeeService) {


this.employeeService = employeeService;
}

@PostMapping("/employee")
public ResponseEntity<Employee> postEmployee(@RequestBody Employee obj)
{
Employee eobj=employeeService.postEmployee(obj);
return new ResponseEntity<Employee>(eobj,HttpStatus.CREATED);
}

@GetMapping("/employee")
public ResponseEntity<List<Employee>> getEmployees()

{
List<Employee> lobj=employeeService.getEmployees();
return new ResponseEntity<List<Employee>>(lobj, HttpStatus.OK);
}

@GetMapping("/employee/{employeeId}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable Long employeeId)
{
Employee obj=employeeService.getEmployeeById(employeeId);
return new ResponseEntity<Employee>(obj,HttpStatus.OK);
}

package com.examly.springapp.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.examly.springapp.model.Payroll;
import com.examly.springapp.service.PayrollService;

@RestController
public class PayRollController {
private PayrollService payrollService;

public PayRollController(PayrollService payrollService) {


this.payrollService = payrollService;
}
@PostMapping("/employee/{employeeId}/payroll")
public ResponseEntity<Payroll> postPayroll(@PathVariable Long employeeId,
@RequestBody Payroll payroll)
{
Payroll obj=payrollService.postPayroll(employeeId,payroll);
return new ResponseEntity<Payroll>(obj,HttpStatus.CREATED);
}
@GetMapping("employee/{employeeId}/payroll")
public ResponseEntity<Payroll> getPayroll(@PathVariable Long employeeId)
{
Payroll pay=payrollService.getPayroll(employeeId);
return new ResponseEntity<Payroll>(pay,HttpStatus.OK);
}
}

package com.examly.springapp.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonManagedReference;

@Entity
public class Employee {
@Id
private Long employeeId;
private String employeeNmae;
private int age;
private Long mobile;
@OneToOne(mappedBy = "employee" ,cascade = CascadeType.ALL)
@JsonManagedReference
private Payroll payroll;

public Employee()
{

public Employee(Long employeeId, String employeeNmae, int age, Long mobile, Payroll
payroll) {
this.employeeId = employeeId;
this.employeeNmae = employeeNmae;
this.age = age;
this.mobile = mobile;
this.payroll = payroll;
}

public Long getEmployeeId() {


return employeeId;
}

public void setEmployeeId(Long employeeId) {


this.employeeId = employeeId;
}

public String getEmployeeNmae() {


return employeeNmae;
}

public void setEmployeeNmae(String employeeNmae) {


this.employeeNmae = employeeNmae;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public Payroll getPayroll() {


return payroll;
}
public void setPayroll(Payroll payroll) {
this.payroll = payroll;
}

public Long getMobile() {


return mobile;
}

public void setMobile(Long mobile) {


this.mobile = mobile;
}
}

package com.examly.springapp.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;

import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity
public class Payroll {
@Id
private Long payrollId;
private double amount;
private int noOfDaysWorked;
@OneToOne
@JsonBackReference
private Employee employee;
public Payroll()
{
}
public Payroll(Long payrollId, double amount, int noOfDaysWorked, Employee employee)
{
this.payrollId = payrollId;
this.amount = amount;
this.noOfDaysWorked = noOfDaysWorked;
this.employee = employee;
}

public Long getPayrollId() {


return payrollId;
}
public void setPayrollId(Long payrollId) {
this.payrollId = payrollId;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public int getNoOfDaysWorked() {
return noOfDaysWorked;
}
public void setNoOfDaysWorked(int noOfDaysWorked) {
this.noOfDaysWorked = noOfDaysWorked;
}

public Employee getEmployee() {


return employee;
}

public void setEmployee(Employee employee) {


this.employee = employee;
}

package com.examly.springapp.repository;

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

import com.examly.springapp.model.Employee;

@Repository
public interface EmployeeRepo extends JpaRepository<Employee,Long>{

package com.examly.springapp.repository;

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

import com.examly.springapp.model.Payroll;

@Repository
public interface PayrollRepo extends JpaRepository<Payroll,Long>{

package com.examly.springapp.service;

import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.examly.springapp.model.Payroll;
import com.examly.springapp.repository.PayrollRepo;

@Service
public class PayrollService {
private PayrollRepo payrollRepo;

public PayrollService(PayrollRepo payrollRepo) {


this.payrollRepo = payrollRepo;
}
private Map<Long,Payroll> map=new HashMap<>();
public Payroll postPayroll(Long employeeId,Payroll payroll)
{
map.put(employeeId,payroll);
return payroll;
}
public Payroll getPayroll(Long employeeId)
{
return payrollRepo.findById(employeeId).orElse(null);
}
}

package com.examly.springapp.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.examly.springapp.model.Employee;
import com.examly.springapp.repository.EmployeeRepo;

@Service
public class EmployeeService {
private EmployeeRepo employeeRepo;

public EmployeeService(EmployeeRepo employeeRepo) {


this.employeeRepo = employeeRepo;
}

public Employee postEmployee(Employee obj)


{
return employeeRepo.save(obj);
}
public List<Employee >getEmployees()
{
return employeeRepo.findAll();
}
public Employee getEmployeeById(Long employeeId)
{
return employeeRepo.findById(employeeId).orElse(null);
}
}
Ex-16 Managing Person details by integrating comprehensive
logging capabilities

package com.examly.springapp.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
@Id
private int id;
private String firstName,lastName;
public Person()
{

}
public Person(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
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;
}

}
package com.examly.springapp.repository;

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

import com.examly.springapp.model.Person;

@Repository
public interface PersonRepository extends JpaRepository <Person,Integer> {

package com.examly.springapp.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.examly.springapp.model.Person;
import com.examly.springapp.repository.PersonRepository;

@Service
public class PersonService {
private PersonRepository personRepo;

public PersonService(PersonRepository personRepo) {


this.personRepo = personRepo;
}
public Person postPerson(Person p)
{
return personRepo.save(p);
}
public List<Person> getAllPersons()
{
return personRepo.findAll();
}
}

package com.examly.springapp.controller;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.examly.springapp.model.Person;
import com.examly.springapp.service.PersonService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
public class PersonController {
private static final Logger lobj=LoggerFactory.getLogger(PersonController.class);
private PersonService personService;

public PersonController(PersonService personService) {


this.personService = personService;
}
@PostMapping("/persons")
public ResponseEntity<Person> postPerson(Person p)
{
try {
lobj.info("POST Request received for /persons");
return new ResponseEntity<>(personService.postPerson(p),HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.OK);
}
}
@GetMapping("/persons")
public ResponseEntity<List<Person>> getAllPersons()
{
try {
lobj.info("GET Request received for /persons");
return new ResponseEntity<>(personService.getAllPersons(),HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Ex-17 Implementation of AOP

MyAspect.java
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyAspect {

@Before("execution(* MyService.doSomething(..))")
public void beforeAdvice() {
System.out.println("Before advice: Executing before doSomething()");
}

@After("execution(* MyService.doSomething(..))")
public void afterAdvice() {
System.out.println("After advice: Executing after doSomething()");
}

@Around("execution(* MyService.doSomething(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Around advice: Executing before doSomething()");
Object result = joinPoint.proceed(); // Execute the target method
System.out.println("Around advice: Executing after doSomething()");
return result;
}
}

MyService.java

import org.springframework.stereotype.Service;

@Service

public class MyService {

public void doSomething() {

System.out.println("Inside MyService.doSomething()");
}

App.java

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {

public static void main(String[] args) {

// Initialize the Spring application context

try (AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext(AppConfig.class)) {

// Retrieve the MyService bean

MyService myService = context.getBean(MyService.class);

// Call the doSomething method

myService.doSomething();

AppConfig.java

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan(basePackages = " com.examly.springapp")

@EnableAspectJAutoProxy

public class AppConfig {

Sample Output

System.out.println("Before advice: Executing before doSomething()");

System.out.println("Around advice: Executing before doSomething()");

System.out.println("Around advice: Executing after doSomething()");

System.out.println("After advice: Executing after doSomething()");

You might also like