MSC (CS-IT) CCT in Java NEP 2020-June-2023 Pattern Practical Journal
MSC (CS-IT) CCT in Java NEP 2020-June-2023 Pattern Practical Journal
Package com.example.simplespringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SimplespringbootApplication {
//HelloController
package com.example.simplespringboot;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/getString")
private String getString()
{
return "This is the first Spring Boot Practical";
}
//pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
/**********************************OUTPUT**********************************/
/** Practical 2: Practical for Restful spring boot application. **/
//entity
package com.example.student.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.persistence.*;
// Annotations
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
// Class
@jakarta.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
//Controller
package com.example.student.controller;
import com.example.student.entity.Department;
import com.example.student.service.DepartmentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
// Annotation
@RestController
// Class
// Annotation
// Save operation
@PostMapping("/departments")
return departmentService.saveDepartment(department);
}
// Read operation
@GetMapping("/departments")
return departmentService.fetchDepartmentList();
// Update operation
@PutMapping("/departments/{id}")
public Department
return departmentService.updateDepartment(
department, departmentId);
// Delete operation
@DeleteMapping("/departments/{id}")
Long departmentId)
departmentService.deleteDepartmentById(
departmentId);
//service
package com.example.student.service;
import com.example.student.entity.Department;
import java.util.List;
// Interface
// Save operation
// Read operation
List<Department> fetchDepartmentList();
// Update operation
// Delete operation
//DEPARTMENTSERVICEIMPL
package com.example.student.service;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
// Annotation
@Service
// Class
implements DepartmentService {
@Autowired
// Save operation
@Override
return departmentRepository.save(department);
// Read operation
return (List<Department>)
departmentRepository.findAll();
}
// Update operation
@Override
public Department
updateDepartment(Department department,
Long departmentId)
Department depDB
= departmentRepository.findById(departmentId)
.get();
if (Objects.nonNull(department.getDepartmentName())
&& !"".equalsIgnoreCase(
department.getDepartmentName())) {
depDB.setDepartmentName(
department.getDepartmentName());
if (Objects.nonNull(
department.getDepartmentAddress())
&& !"".equalsIgnoreCase(
department.getDepartmentAddress())) {
depDB.setDepartmentAddress(
department.getDepartmentAddress());
}
if (Objects.nonNull(department.getDepartmentCode())
&& !"".equalsIgnoreCase(
department.getDepartmentCode())) {
depDB.setDepartmentCode(
department.getDepartmentCode());
return departmentRepository.save(depDB);
// Delete operation
@Override
departmentRepository.deleteById(departmentId);
//repository
package com.example.student.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.student.entity.Department;
// Annotation
@Repository
// Interface
public interface DepartmentRepository
//DepartmentApplication
package com.example.student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(DepartmentApplication.class, args);
//deparment application
package com.example.student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(DepartmentApplication.class, args);
//Appliocation.properties
server.port=8082
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=msc@1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql:true
//pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.4</version>
</parent>
<groupId>com.example</groupId>
<artifactId>student</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>student</name>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Output:
MYSQL WORKBEnCH
CREATE operation
READ operation
UPDATE operation
DELETE operation
/** Practical 3: Practical to create student entity using CRUD Operation with
exception handling create spring boot (use hibernate mysql for backend) **/
//Student.java
package com.example.studentprojects.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
//import jakarta.persistence.Table;
@Entity
//@Table (name = "Student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column (name = "StudID")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// StudentRepository.java
package com.example.studentprojects.repository;
import com.example.studentprojects.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
//StudentService.java
package com.example.studentprojects.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import com.example.studentprojects.repository.StudentRepository;
import com.example.studentprojects.entity.Student;
import com.example.studentprojects.exception.StudentNotFoundException;
@Service
public class StudentService {
private final StudentRepository studentRepository;
@Autowired
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
//StudentNotFoundException.java
package com.example.studentprojects.exception;
public class StudentNotFoundException extends RuntimeException {
public StudentNotFoundException(String message) {
super(message);
}
}
// StudentController.java
package com.example.studentprojects.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import com.example.studentprojects.service.StudentService;
import com.example.studentprojects.entity.Student;
import com.example.studentprojects.exception.StudentNotFoundException;
import java.util.List;
@RestController
@RequestMapping("/api/students")
public class StudentController {
@GetMapping
public List<Student> getAllStudents() {
return studentService.getAllStudents();
}
@GetMapping("/{id}")
public Student getStudentById(@PathVariable Long id) {
return studentService.getStudentById(id);
}
@PostMapping
public void saveStudent(@RequestBody Student student) {
studentService.saveStudent(student);
}
@PutMapping("/{id}")
public void updateStudent(@PathVariable Long id, @RequestBody Student student) {
student.setId(id);
studentService.saveStudent(student);
}
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
}
@ExceptionHandler(StudentNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleStudentNotFound(StudentNotFoundException ex) {
return ex.getMessage();
}
}
// application.properties
server.port=8082
# Configuration for MySQL Database
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/studdb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=msc@1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql:true
// pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
/**********************************OUTPUT**********************************/
// Create Operation
//Retrieve Operation
//Update Operation
//Delete Operation
// Exception
//Employee.java
package com.example.employeeprojects.entity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import jakarta.transaction.Transactional;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Entity
@Transactional
@Data
@NoArgsConstructor
@Table(name = "employee_details")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "emp_id")
private Long empId;
private String empName;
private Integer empAge;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fk_add_id")
// @OneToMany(cascade = CascadeType.ALL)
// @JoinColumn(name = "fk_emp_id", referencedColumnName = "emp_id")
private Address address;
// private List<Address> address;
}
//Address.java
package com.example.employeeprojects.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import jakarta.transaction.Transactional;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Transactional
@Data
@NoArgsConstructor
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "add_id")
private Long addressid;
private String city;
private String addressType;
@OneToOne(mappedBy = "address")
private Employee employee;
}
//EmployeeRepository.java
package com.example.employeeprojects.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.employeeprojects.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee,Long>{
}
//AddressRepository.java
package com.example.employeeprojects.repository;
import org. springframework.data.jpa.repository.JpaRepository;
import com.example.employeeprojects.entity.Address;
public interface AddressRepository extends JpaRepository<Address,Long>{
}
//EmployeeController.java
package com.example.employeeprojects.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import com.example.employeeprojects.entity.Employee;
import com.example.employeeprojects.repository.EmployeeRepository;
@RestController
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@PostMapping("/saveEmployees")
public ResponseEntity<String> saveEmployees(@RequestBody List<Employee> empData){
employeeRepository.saveAll(empData);
return ResponseEntity.ok("Data Saved");
}
}
//application.properties
server.port=8086
# Configuration for MySQL Database
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/empdb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=msc@1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql:true
/**********************************OUTPUT**********************************/
// Table: empdb.employee_details
// Table: empdb.address
/** Practical 5: Develop an employee entity where the user can create
employee data. Use Hibernate to map the address entity and its relationship
(one-to-many) with employee entity. **/
//Employee.java
package com.example.employeeprojects.entity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import jakarta.transaction.Transactional;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Entity
@Transactional
@Data
@NoArgsConstructor
@Table(name = "employee_details")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "emp_id")
private Long empId;
private String empName;
private Integer empAge;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "fk_emp_id", referencedColumnName = "emp_id")
//Address.java
package com.example.employeeprojects.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
//import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import jakarta.transaction.Transactional;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Transactional
@Data
@NoArgsConstructor
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "add_id")
private Long addressid;
private String city;
private String addressType;
}
//EmployeeRepository.java
package com.example.employeeprojects.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.employeeprojects.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee,Long>{
}
//AddressRepository.java
package com.example.employeeprojects.repository;
import org. springframework.data.jpa.repository.JpaRepository;
import com.example.employeeprojects.entity.Address;
public interface AddressRepository extends JpaRepository<Address,Long>{
}
//EmployeeController.java
package com.example.employeeprojects.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import com.example.employeeprojects.entity.Employee;
import com.example.employeeprojects.repository.EmployeeRepository;
@RestController
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@PostMapping("/saveEmployees")
public ResponseEntity<String> saveEmployees(@RequestBody List<Employee> empData){
employeeRepository.saveAll(empData);
return ResponseEntity.ok("Data Saved");
}
//application.properties
server.port=8082
# Configuration for MySQL Database
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/empdb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=msc@1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql:true
/**********************************OUTPUT**********************************/
// Table: empdb.employee_details
// Table: empdb.address
/**Practical 6: Develop the micro service for employee management
implement endpoint for retrieve employee details. Utilize spring boot and
spring JPA to store and retrieve employee data. **/
// Employee.java
package com.example.employeemicroserviceproject.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "age")
private String age;
//EmployeeRepository.java
package com.example.employeemicroserviceproject.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.employeemicroserviceproject.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee,Long>{
}
//EmployeeService.java
package com.example.employeemicroserviceproject.service;
import com.example.employeemicroserviceproject.entity.Employee;
import com.example.employeemicroserviceproject.repository.EmployeeRepository;
import com.example.employeemicroserviceproject.response.EmployeeResponse;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Optional;
@Autowired
private ModelMapper mapper;
public EmployeeResponse getEmployeeById(long id) {
Optional<Employee> employee = employeeRepo.findById(id);
EmployeeResponse employeeResponse = mapper.map(employee,
EmployeeResponse.class);
return employeeResponse;
}
}
//EmployeeController.java
package com.example.employeemicroserviceproject.controller;
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.RestController;
import com.example.employeemicroserviceproject.response.EmployeeResponse;
import com.example.employeemicroserviceproject.service.EmployeeService;
@RestController
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/employees/{id}")
private ResponseEntity<EmployeeResponse> getEmployeeDetails(@PathVariable("id") int
id) {
EmployeeResponse employee = employeeService.getEmployeeById(id);
return ResponseEntity.status(HttpStatus.OK).body(employee);
}
}
//EmployeeResponse.java
package com.example.employeemicroserviceproject.response;
package com.example.employeemicroserviceproject.configuration;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.employeemicroserviceproject.service.EmployeeService;
@Configuration
public class EmployeeConfig {
@Bean
public EmployeeService employeeBean() {
return new EmployeeService();
}
@Bean
public ModelMapper modelMapperBean() {
return new ModelMapper();
}
//application.properties
server.port=8086
//Book.java
package com.example.librarymgmtsystem.entity;
import java.util.*;
import jakarta.persistence.*;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Book(Long id, String title, Set<User> borrowers) {
this.id = id;
this.title = title;
this.borrowers = borrowers;
}
@ManyToMany(mappedBy = "borrowedBooks")
private Set<User> borrowers = new HashSet<>();
public Book() {
}
//User.java
package com.example.librarymgmtsystem.entity;
import java.util.*;
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Long getId() {
return id;
}
@ManyToMany
@JoinTable(name = "user_books",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "book_id"))
private Set<Book> borrowedBooks = new HashSet<>();
public User() {
}
//BookRepository.java
package com.example.librarymgmtsystem.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.librarymgmtsystem.entity.Book;
public interface BookRepository extends JpaRepository<Book,Long>{
}
//UserRepository.java
package com.example.librarymgmtsystem.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.librarymgmtsystem.entity.User;
public interface UserRepository extends JpaRepository<User,Long>{
}
// BookService.java
package com.example.librarymgmtsystem.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.librarymgmtsystem.entity.Book;
import com.example.librarymgmtsystem.exception.BookNotFoundException;
import com.example.librarymgmtsystem.repository.BookRepository;
@Service
public class BookService {
private BookRepository bookRepository;
@Autowired
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
return bookRepository.save(existingBook);
}
// UserService.java
package com.example.librarymgmtsystem.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.librarymgmtsystem.entity.Book;
import com.example.librarymgmtsystem.entity.User;
import com.example.librarymgmtsystem.exception.BookNotFoundException;
import com.example.librarymgmtsystem.exception.UserNotFoundException;
import com.example.librarymgmtsystem.repository.BookRepository;
import com.example.librarymgmtsystem.repository.UserRepository;
import java.util.HashSet;
import java.util.Set;
@Service
public class UserService {
private UserRepository userRepository;
private BookRepository bookRepository;
@Autowired
public UserService(UserRepository userRepository, BookRepository bookRepository) {
this.userRepository = userRepository;
this.bookRepository = bookRepository;
}
// LibraryService.java
package com.example.librarymgmtsystem.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.librarymgmtsystem.entity.Book;
import com.example.librarymgmtsystem.entity.User;
import com.example.librarymgmtsystem.exception.BookNotFoundException;
import com.example.librarymgmtsystem.exception.UserNotFoundException;
import com.example.librarymgmtsystem.repository.BookRepository;
import com.example.librarymgmtsystem.repository.UserRepository;
@Service
public class LibraryService {
@Autowired
private BookRepository bookRepository;
@Autowired
private UserRepository userRepository;
// BookNotFoundException.java
package com.example.librarymgmtsystem.exception;
// UserNotFoundException.java
package com.example.librarymgmtsystem.exception;
// LibraryController.java
package com.example.librarymgmtsystem.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.librarymgmtsystem.entity.Book;
import com.example.librarymgmtsystem.entity.User;
import com.example.librarymgmtsystem.service.BookService;
import com.example.librarymgmtsystem.service.UserService;
import java.util.Set;
@RestController
@RequestMapping("/library")
public class LibraryController {
@Autowired
private UserService userService;
@Autowired
private BookService bookService;
// Get a user by ID
@GetMapping("/users/{userId}")
public User getUser(@PathVariable Long userId) {
return userService.getUserById(userId);
}
// Get a book by ID
@GetMapping("/books/{bookId}")
public Book getBook(@PathVariable Long bookId) {
return bookService.getBookById(bookId);
}
// Borrow a book
@PostMapping("/users/{userId}/borrow/{bookId}")
public ResponseEntity<String> borrowBook(@PathVariable Long userId, @PathVariable
Long bookId) {
userService.borrowBook(userId, bookId);
return ResponseEntity.ok("Book borrowed");
}
// Return a book
@PostMapping("/users/{userId}/return/{bookId}")
public ResponseEntity<String> returnBook(@PathVariable Long userId, @PathVariable Long
bookId) {
userService.returnBook(userId, bookId);
return ResponseEntity.ok("Book returned");
}
}
// application.properties
server.port=8082
// pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>librarymgmtsystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>librarymgmtsystem</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
/**********************************OUTPUT**********************************/
// Create Operation
//Retrieve Operation
import java.util.*;
import jakarta.persistence.*;
@Entity
public class Blog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Long getId() {
return id;
}
@OneToMany(mappedBy = "blog")
private List<Comment> comments = new ArrayList<>();
//Comment.java
package com.example.blogmgmtsystem.entity;
import jakarta.persistence.*;
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Long getId() {
return id;
}
@ManyToOne
@JoinColumn(name = "blog_id")
private Blog blog;
//User.java
package com.example.blogmgmtsystem.entity;
import java.util.*;
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Long getId() {
return id;
}
//BlogRepository.java
package com.example.blogmgmtsystem.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.blogmgmtsystem.entity.Blog;
//CommentRepository.java
package com.example.blogmgmtsystem.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.blogmgmtsystem.entity.Blog;
import com.example.blogmgmtsystem.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.blogmgmtsystem.entity.User;
//BlogService.java
package com.example.blogmgmtsystem.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.blogmgmtsystem.entity.Blog;
import com.example.blogmgmtsystem.entity.Comment;
import com.example.blogmgmtsystem.exception.BlogNotFoundException;
import com.example.blogmgmtsystem.repository.BlogRepository;
import com.example.blogmgmtsystem.repository.CommentRepository;
import java.util.List;
import java.util.Optional;
@Service
public class BlogService {
@Autowired
public BlogService(BlogRepository blogRepository, CommentRepository
commentRepository) {
this.blogRepository = blogRepository;
this.commentRepository = commentRepository;
}
return commentRepository.findByBlog(blog);
}
public Comment addCommentToBlog(Long blogId, Comment comment) {
Blog blog = blogRepository.findById(blogId).orElseThrow(() -> new
BlogNotFoundException("Blog with ID " + blogId + " not found."));
}
//CommentService.java
package com.example.blogmgmtsystem.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.blogmgmtsystem.entity.Blog;
import com.example.blogmgmtsystem.entity.Comment;
import com.example.blogmgmtsystem.exception.BlogNotFoundException;
import com.example.blogmgmtsystem.exception.CommentNotFoundException;
import com.example.blogmgmtsystem.repository.BlogRepository;
import com.example.blogmgmtsystem.repository.CommentRepository;
@Service
public class CommentService {
private CommentRepository commentRepository;
private BlogRepository blogRepository;
@Autowired
public CommentService(CommentRepository commentRepository, BlogRepository
blogRepository) {
this.commentRepository = commentRepository;
this.blogRepository = blogRepository;
}
//UserService.java
package com.example.blogmgmtsystem.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.blogmgmtsystem.entity.User;
import com.example.blogmgmtsystem.exception.UserNotFoundException;
import com.example.blogmgmtsystem.repository.UserRepository;
import java.util.List;
@Service
public class UserService {
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
//BlogNotFoundException.java
package com.example.blogmgmtsystem.exception;
//CommentNotFoundException.java
package com.example.blogmgmtsystem.exception;
//UserNotFoundException.java
package com.example.blogmgmtsystem.exception;
//BlogController.java
package com.example.blogmgmtsystem.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.blogmgmtsystem.service.*;
import com.example.blogmgmtsystem.entity.*;
@RestController
@RequestMapping("/blogs")
public class BlogController {
@Autowired
private BlogService blogService;
@Autowired
private UserService userService;
@Autowired
private CommentService commentService;
@PostMapping("/createUser")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@GetMapping("/users/{userId}")
public User getUserById(@PathVariable Long userId) {
return userService.getUserById(userId);
}
//Delete a comment
@DeleteMapping("/comments/{commentId}")
public ResponseEntity<String> deleteComment(@PathVariable Long commentId) {
commentService.deleteComment(commentId);
return ResponseEntity.ok("Comment Deleted");
}
}
//application.properties
server.port=8084
</project>
/**********************************OUTPUT**********************************/
//Create User, Blog and Comment
// Retrieve Blogs, Users and Comments
//Update Blog
//Delete a comment
//Auto-updating MYSQL database (Backend)
//comment
//user