Rest-Lab programs
Rest-Lab programs
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;
@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;
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;
@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;
}
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
@Id
public Employee()
this.employeeId = employeeId;
this.employeeName = employeeName;
this.employeeEmail = employeeEmail;
this.salary = salary;
this.department = department;
return employeeId;
this.employeeId = employeeId;
return employeeName;
this.employeeName = employeeName;
return employeeEmail;
this.employeeEmail = employeeEmail;
}
public double getSalary() {
return salary;
this.salary = salary;
return 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")
this.employeeService = employeeService;
@PostMapping("/employee")
Employee obj=employeeService.addEmployee(e);
@PutMapping("/employee/{employeeId}")
if (employeeService.updateEmployee(employeeId,e)==true) {
@DeleteMapping("/employee/{employeeId}")
if (employeeService.deleteEmployeeById(employeeId)==true) {
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
@Autowired
this.employeeRepo = employeeRepo;
return employeeRepo.save(e);
if (employeeRepo.findById(employeeId)!=null) {
employeeRepo.save(e);
return true;
return false;
{
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
}
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
@Id
int babyId;
String babyFirstName,babyLastName,fatherName,motherName,address;
public Children() {
String address) {
this.babyId = babyId;
this.babyFirstName = babyFirstName;
this.babyLastName = babyLastName;
this.fatherName = fatherName;
this.motherName = motherName;
this.address = address;
}
return babyId;
this.babyId = babyId;
return babyFirstName;
this.babyFirstName = babyFirstName;
return babyLastName;
this.babyLastName = babyLastName;
return fatherName;
}
this.fatherName = fatherName;
return motherName;
this.motherName = motherName;
return 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
@Autowired
ChildrenService cs;
//post
@PostMapping("/api/children")
//sorting
@GetMapping("/api/children/sortBy/{field}")
return cs.sort(field);
//pagination
@GetMapping("/api/children/{offset}/{pagesize}")
@GetMapping("/api/children/{offset}/{pagesize}/{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
@Autowired
ChildrenRepo cr;
//post
return cr.save(c);
//sorting by field
Sort sort=Sort.by(Sort.Direction.ASC,field);
return cr.findAll(sort);
}
//pagination
return cr.findAll(page).getContent();
.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;
}
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
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
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;
return personId;
this.personId = personId;
return firstName;
this.firstName = firstName;
return lastName;
this.lastName = lastName;
}
return age;
this.age = age;
return 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
@Autowired
@PostMapping("/api/person")
try {
} catch (Exception e) {
@GetMapping("/api/person")
public ResponseEntity<?>getPerson(){
try {
} catch (Exception e) {
@GetMapping("/api/person/byAge")
try {
} catch (Exception e) {
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
@Autowired
return repo.save(person);
return repo.findAll();
return repo.findAll(sort);
Person_Repository
package com.example.springapp.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.springapp.model.Person;
}
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
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Person()
this.id = id;
this.name = name;
this.age = age;
}
return id;
this.id = id;
return name;
this.name = name;
return 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
this.personService = personService;
@PostMapping("/person")
@GetMapping("/person/startsWithName/{value}")
return new
ResponseEntity<>(personService.getPersonStartingName(value),HttpStatus.OK);
@GetMapping("/person/endsWithName/{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>{
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
this.personRepo = personRepo;
return personRepo.save(p);
return personRepo.findByNameStartsWith(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
@Id
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;
this.personId = personId;
return firstName;
this.firstName = firstName;
return lastName;
this.lastName = lastName;
return gender;
}
public void setGender(String gender) {
this.gender = gender;
return email;
this.email = email;
return 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
this.personService = personService;
@PostMapping("/api/person")
@GetMapping("/api/person/byage/{age}")
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
this.personRepo = personRepo;
return personRepo.save(p);
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
}
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
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
return person;
}
public void setPerson(Person person) {
this.person = person;
@OneToOne
@JsonBackReference
public Address()
this.id = id;
this.street = street;
this.city = city;
this.zipCode = zipCode;
return id;
this.id = id;
}
public String getStreet() {
return street;
this.street = street;
return city;
this.city = city;
return 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
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonManagedReference
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;
return id;
this.id = id;
return name;
this.name = name;
}
public String getEmail() {
return email;
this.email = email;
return phoneNumber;
this.phoneNumber = phoneNumber;
return nationality;
this.nationality = nationality;
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
this.personService = personService;
@PostMapping("address/person/{personId}")
Person pobj=personService.getPersonById(id).orElse(null);
aobj.setPerson(pobj);
addressService.postAddress(aobj);
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
this.personService = personService;
@PostMapping("/person")
Person pobj=personService.postPerson(obj);
@GetMapping("/person")
List<Person> pobj=personService.getPersons();
@GetMapping("/person/{personId}")
Optional<Person> pobj=personService.getPersonById(id);
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
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
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
this.personRepo = personRepo;
return personRepo.save(obj);
}
return personRepo.findAll();
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
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;
}
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;
}
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;
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 {
@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;
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;
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()
{
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()
{
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;
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;
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;
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;
@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;
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;
}
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;
}
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;
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;
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;
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;
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
System.out.println("Inside MyService.doSomething()");
}
App.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
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
Sample Output