Getting Started | Building an Application with Spring Boot
Build an application enterprise with Spring boot and Angular use Jpa
Objective:
In this tutorial We will build an application Company To display departments with code, location and description, employees with name, hiring date, salary etc... and projects with name, description and process. Each employee can have one project or many projects to work on and every user can management the functionality Add, update or delete.
Used Skills in this project:
Java, SpringBoot, MicroServices, REST WebServices, JPA, Hibernate, MySQL Database, Maven, Angular, GitHub, SpringBoot Embedded Tomcat Server, STS-Eclipse IDE
Tools to be used
° Use any IDE to develop the Spring and Hibernate project. It may be STS/Eclipse/Netbeans. Here, we are using STS (Spring Tool Suite).
° Mysql for the database.
° Use any IDE to develop the Angular project. It may be Visual Studio Code/Sublime. Here, we are using Visual Studio Code.
° Server: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.
Spring MVC
Spring MVC is the primary web framework built on the Servlet API. It is build on the popular MVC design pattern. MVC (Model-View-Controller) is a software architecture pattern, which separates application into three areas: model, view, and controller. The model represents a Java object carrying data. The view represents the visualization of the data that the model contains. The controller controls the data flow into model object and updates the view when the data changes. It separates the view and model.
Spring Boot Architecture
Spring Boot is a module of the Spring Framework. It is used to create stand-alone, production-grade Spring Based Applications with minimum efforts. It is developed on top of the core Spring Framework.
Introduction mysql to database
MySQL is a database management system that allows you to manage relational databases. It is open source software backed by Oracle. It means you can use MySQL without paying a dime. Also, if you want, you can change its source code to suit your needs. MySQL can run on various platforms UNIX, Linux, Windows, etc. You can install it on a server or even in a desktop. Besides, MySQL is reliable, scalable, and fast.
Introduction to the POM
POM A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. Examples for this is the build directory, which is target; the source directory, which is src/main/java; the test source directory, which is src/main/java; and so on. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.
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>2.4.1</version>
<relativePath/>
</parent>
<groupId>org.company</groupId>
<artifactId>company</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>company</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</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>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Properties File
Properties files are used to keep ‘N’ number of properties in a single file to run the application in a different environment. In Spring Boot, properties are kept in the application.properties file under the classpath.
The application.properties file is located in the src/main/resources directory. The code for sample application.properties
We need to create database name it bank
src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/company?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.activemq.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
server.port=8080
spring.jpa.database=MYSQL
Class Diagram
Modals / Entities
An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes.
We need to create these entities in modal package
-> Company
-> Department
-> Employee
-> EmployeePhone
-> Project
-> User
Here, we are creating an Entity
Company.java This object content id, name, location, createAt and relational @ManyToOne User and @OneToMany with Department
src/main/java/com/company/model/Company.java):
package com.company.modal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(unique = true)
private String name;
private String location;
@Column(columnDefinition = "TEXT")
private String description;
@Temporal(TemporalType.TIMESTAMP)
private Date createAt;
@ManyToOne
@JsonBackReference(value = "user")
private User user;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "company")
private List<Department> departments;
public Company() {
super();
}
public Company(String name, String location, String description, Date createAt, User user, List<Department> departments) {
super();
this.name = name;
this.location = location;
this.description = description;
this.createAt = createAt;
this.user = user;
this.departments = departments;
}
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 getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Department> getDepartments() {
return departments;
}
public void setDepartments(List<Department> departments) {
this.departments = departments;
}
public void addDepartment(Department department) {
if(getDepartments() == null) {
this.departments = new ArrayList<>();
}
getDepartments().add(department);
department.setCompany(this);
}
}
Here, we are creating an Entity
Department.java This object content id, code, location, createAt and relational @ManyToOne with Company and @OneToMany with Employee and Project
src/main/java/com/company/model/Department.java):
package com.company.modal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(unique = true)
private String code;
private String location;
@Column(columnDefinition = "TEXT")
private String description;
@Temporal(TemporalType.TIMESTAMP)
private Date createAt;
@ManyToOne
@JsonBackReference(value = "company")
private Company company;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
private List<Employee> employees;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
private List<Project> projects;
public Department() {
super();
}
public Department(String code, String location, String description, Date createAt, Company company, List<Employee> employees, List<Project> projects) {
super();
this.code = code;
this.location = location;
this.description = description;
this.createAt = createAt;
this.company = company;
this.employees = employees;
this.projects = projects;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public void addEmployee(Employee employee) {
if(getEmployees() == null) {
this.employees = new ArrayList<>();
}
getEmployees().add(employee);
employee.setDepartment(this);
}
public void addProjectToDepratment(Project project) {
if(getProjects() == null) {
this.projects = new ArrayList<>();
}
getProjects().add(project);
project.setDepartment(this);
}
}
Here, we are creating an Entity
Employee.java This object content id, name, address, salary, hiringDate, birthDate and relational @ManyToOne with Department @OneToMany With EmployeePhone @ManyToMany with Project
src/main/java/com/company/model/Employee.java):
package com.company.modal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String address;
private double salary;
private String hiringDate;
private String birthDate;
@ManyToOne
@JsonBackReference("department")
private Department department;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "employee")
private List<EmployeePhone> employeePhones;
@JsonProperty(access = Access.WRITE_ONLY)
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "employee_projects", joinColumns = @JoinColumn(name = "project_id"), inverseJoinColumns = @JoinColumn(name = "employee_id"))
private List<Project> projects;
public Employee() {
super();
}
public Employee(String name, String address, double salary, String hiringDate, String birthDate, Department department, List<EmployeePhone> employeePhones, List<Project> projects) {
super();
this.name = name;
this.address = address;
this.salary = salary;
this.hiringDate = hiringDate;
this.birthDate = birthDate;
this.department = department;
this.employeePhones = employeePhones;
this.projects = projects;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getHiringDate() {
return hiringDate;
}
public void setHiringDate(String hiringDate) {
this.hiringDate = hiringDate;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public List<EmployeePhone> getEmployeePhones() {
return employeePhones;
}
public void setEmployeePhones(List<EmployeePhone> employeePhones) {
this.employeePhones = employeePhones;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public void addEmployeePhone(EmployeePhone employeePhone) {
if (getEmployeePhones() == null) {
this.employeePhones = new ArrayList<>();
}
getEmployeePhones().add(employeePhone);
employeePhone.setEmployee(this);
}
public void addProjectToEmploye(Project project) {
if (getProjects() == null) {
this.projects = new ArrayList<>();
}
if (!getProjects().contains(project)) {
getProjects().add(project);
}
}
}
Here, we are creating an Entity
Arbitrate.java This object content id, phone, and relational @ManyToOne with Employee
src/main/java/com/company/model/Arbitrate.java):
package com.company.modal;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
public class EmployeePhone {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String phone;
@ManyToOne
@JsonBackReference(value = "employee")
private Employee employee;
public EmployeePhone() {
super();
}
public EmployeePhone(String phone, Employee employee) {
super();
this.phone = phone;
this.employee = employee;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Employee getEmployee() {
return employee;
}
public voidsetEmployee(Employee employee) {
this.employee = employee;
}
}
Here, we are creating an Entity
Project.java This object content id, name, location, createAt and relational @ManyToOne with Employee and Department
src/main/java/com/company/model/Project.java):
package com.company.modal;
import java.util.Date;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(unique = true)
private String name;
@Column(columnDefinition = "TEXT")
private String description;
@Temporal(TemporalType.TIMESTAMP)
private Date createAt;
@Enumerated(EnumType.STRING)
private Process process;
@ManyToOne
@JsonBackReference(value = "employee")
private Employee employee;
@ManyToOne
@JsonBackReference(value = "department")
private Department department;
public Project() {
super();
}
public Project(String name, String description, Date createAt, Process process, Employee employee, Department department) {
super();
this.name = name;
this.description = description;
this.createAt = createAt;
this.process = process;
this.employee = employee;
this.department = department;
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public Process getProcess() {
return process;
}
public voidsetProcess(Process process) {
this.process = process;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
Here, we are creating an Entity
User.java This object content id, username, password, admin and relational @ManyToOne with Company
src/main/java/com/company/model/User.java):
package com.company.modal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String username;
private String password;
private boolean admin;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<Company> companies;
public User() {
super();
}
public User(String username, String password, boolean admin, List<Company> companies) {
super();
this.username = username;
this.password = password;
this.admin = admin;
this.companies = companies;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public List<Company> getCompanies() {
return companies;
}
public void setCompanies(List<Company> companies) {
this.companies = companies;
}
public void addCompany(Company company) {
if (getCompanies() == null) {
this.companies = new ArrayList<>();
}
getCompanies().add(company);
company.setUser(this);
}
}
Here, we are creating an enum Process
src/main/java/com/company/model/Process.java):
package com.company.modal;
public enum Process {
TODO, WORKON, DONE
}
Spring Data JPA Projections
When using Spring Data JPA to implement the persistence layer, the repository typically returns one or more instances of the root class. However, more often than not, we don't need all the properties of the returned objects.
In such cases, it may be desirable to retrieve data as objects of customized types. These types reflect partial views of the root class, containing only properties we care about. This is where projections come in handy.
We need to create these interface dao
-> CompanyDao
-> DepartmentDao
-> EmployeeDao
-> EmployeePhoneDao
-> ProjectDao
-> UserDao
Here, we are creating an interface CompanyDao
src/main/java/com/company/dao/CompanyDao.java):
package com.company.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.company.modal.Company;
@Repository
public interface CompanyDao extends JpaRepository<Company, Long>{
}
Here, we are creating an interface DepartmentDao
src/main/java/com/company/dao/DepartmentDao.java):
package com.company.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.company.modal.Department;
@Repository
public interface DepartmentDao extends JpaRepository<Department, Long>{
}
Here, we are creating an interface EmployeeDao
src/main/java/com/company/dao/EmployeeDao.java):
package com.company.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.company.modal.Employee;
@Repository
public interface EmployeeDao extends JpaRepository<Employee, Long>{
}
Here, we are creating an interface EmployeePhoneDao
src/main/java/com/company/dao/EmployeePhoneDao.java):
package com.company.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.company.modal.EmployeePhone;
@Repository
public interface EmployeePhoneDao extends JpaRepository<EmployeePhone, Long>{
}
Here, we are creating an interface ProjectDao
src/main/java/com/company/dao/ProjectDao.java):
package com.company.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.company.modal.Project;
@Repository
public interface ProjectDao extends JpaRepository<Project, Long>{
}
Here, we are creating an interface UserDao
src/main/java/com/company/dao/UserDao.java):
package com.company.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.company.modal.User;
@Repository
public interface UserDao extends JpaRepository<User, Long>{
}
The services
Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here
We will create these interfaces in service package:
-> CompanyService
-> DepartmentService
-> EmployeeService
-> EmployeePhoneService
-> ProjectService
-> UserService
Here, we are creating an interface CompanyService
src/main/java/com/company/service/CompanyService.java):
package com.company.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.company.modal.Company;
@Service
public interface CompanyService {
Company addCompany(Company company, long id);
Company editCompany(Company company, long id);
Company findCompany(long id);
void deleteCompany(long id);
List<Company> findCompanies();
}
Here, we are creating an interface DepartmentService
src/main/java/com/company/service/DepartmentService.java):
package com.company.service;
import com.company.modal.Department;
@Service
public interface DepartmentService {
Department addDepartment(Department department, long id);
Department editDepartment(Department department, long id);
Department findDepartment(long id);
void deleteDepartment(long id);
}
Here, we are creating an interface EmployeePhoneService
src/main/java/com/company/service/EmployeePhoneService.java):
package com.company.service;
import java.util.List;
import com.company.modal.EmployeePhone;
@Service
public interface EmployeePhoneService {
EmployeePhone addEmployeePhone(EmployeePhone employeePhone, long id);
EmployeePhone editEmployeePhone(EmployeePhone employeePhone, long id);
void deleteEmployeePhone(long id);
List<EmployeePhone> findEmployeePhones(long id);
EmployeePhone findEmployeePhone(long id);
}
Here, we are creating an interface EmployeeService
src/main/java/com/company/service/EmployeeService.java):
package com.company.service;
import java.util.List;
import com.company.modal.Employee;
@Service
public interface EmployeeService {
Employee addEmployee(Employee employee, long id);
Employee editEmployee(Employee employee, long id);
Employee findEmployee(long id);
void deleteEmployee(long id);
List<Employee> findEmployees();
}
Here, we are creating an interface ProjectService
src/main/java/com/company/service/ProjectService.java):
package com.company.service;
import java.util.List;
import com.company.modal.Project;
@Service
public interface ProjectService {
Project addProjectToEmployee(long idEmployee, long idProject);
Project addProjectToDeprtment(Project project, long id);
Project editProject(Project project, long id;
Project findProject(long id);
void deleteProejct(long id);
List<Project> findProjectsForEmplopyee(long id);
List<Project> findProjects();
void deleteProjectFromEmployee(long idEmployee, long idProject);
}
Here, we are creating an interface UserService
src/main/java/com/company/model/UserService.java):
package com.company.service;
import java.util.List;
import com.company.modal.User;
@Service
public interface UserService {
User addUser(User user);
List<User> findAllUsers();
User editUser(User user, long id);
User findUserById(long id);
void deleteUser(long id);
User findByUsername(String username);
}
The managers classes implementation
An impl class is usually a class that implements the behaviour described by one of these interfaces. While the internal implementation class, With transactions configured, we can now annotation a bean with @Transactional and @Service either at the class or method level. Then conversion Entity to DTO. This is stands for Data Transfer Object and is a simple Plain Old Java Object which contains class properties and getters and settings methods for accessing those properties.
We will create these class in the impl package
-> CompanyServiceImpl
-> DepartmentServiceImpl
-> EmployeeService
-> EmployeePhoneServiceImpl
-> ProjectServiceImpl
-> UserServiceImpl
Here, we are creating a class CompanyServiceImpl
src/main/java/com/company/impl/CompanyServiceImpl.java):
package com.company.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.company.dao.CompanyDao;
import com.company.dao.UserDao;
import com.company.modal.Company;
import com.company.modal.User;
import com.company.service.CompanyService;
@Transactional
@Component
public class CompanyServiceImpl implements CompanyService{
@Autowired
private CompanyDao companyDao;
@Autowired
private UserDao userDao;
@Override
public Company addCompany(Company company, long id) {
User user = userDao.findById(id).orElse(null);
company.setCreateAt(new Date());
user.addCompany(company);
return companyDao.save(company);
}
@Override
public Company editCompany(Company company, long id) {
Company existCompany = companyDao.findById(id).get();
existCompany.setName(company.getName());
existCompany.setDescription(company.getDescription());
existCompany.setLocation(company.getLocation());
return companyDao.save(existCompany);
}
@Override
public Company findCompany(long id) {
return companyDao.findById(id).get();
}
@Override
public void deleteCompany(long id) {
companyDao.deleteById(id);
}
@Override
public List<Company> findCompanies() {
return companyDao.findAll();
}
}
Here, we are creating a class DepartmentServiceImpl
src/main/java/com/company/impl/DepartmentServiceImpl.java):
package com.company.impl;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.company.dao.CompanyDao;
import com.company.dao.DepartmentDao;
import com.company.modal.Company;
import com.company.modal.Department;
import com.company.service.DepartmentService;
@Transactional
@Component
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentDao departmentDao;
@Autowired
private CompanyDao companyDao;
@Override
public Department addDepartment(Department department, long id) {
Company company = companyDao.findById(id).get();
department.setCreateAt(new Date());
company.addDepartment(department);
return departmentDao.save(department);
}
@Override
publicDepartment editDepartment(Department department, long id) {
Department existDepartment = departmentDao.findById(id).get();
existDepartment.setCode(department.getCode());
existDepartment.setLocation(department.getLocation());
existDepartment.setDescription(department.getDescription());
return departmentDao.save(existDepartment);
}
@Override
public Department findDepartment(long id) {
return departmentDao.findById(id).get();
}
@Override
public void deleteDepartment(long id) {
departmentDao.deleteById(id);
}
}
Here, we are creating a class EmployeePhoneServiceImpl
src/main/java/com/company/impl/EmployeePhoneServiceImpl.java):
package com.company.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.company.dao.EmployeeDao;
import com.company.dao.EmployeePhoneDao;
import com.company.modal.Employee;
import com.company.modal.EmployeePhone;
import com.company.service.EmployeePhoneService;
@Transactional
@Component
public class EmployeePhoneServiceImpl implements EmployeePhoneService {
@Autowired
private EmployeePhoneDao employeePhoneDao;
@Autowired
private EmployeeDao employeeDao;
@Override
public EmployeePhone addEmployeePhone(EmployeePhone employeePhone, long id) {
Employee employee = employeeDao.findById(id).get();
employee.addEmployeePhone(employeePhone);
return employeePhoneDao.save(employeePhone);
}
@Override
public EmployeePhone editEmployeePhone(EmployeePhone employeePhone, long id) {
EmployeePhone exsitEmployeePhone = employeePhoneDao.findById(id).get();
exsitEmployeePhone.setPhone(employeePhone.getPhone());
return employeePhoneDao.save(exsitEmployeePhone);
}
@Override
public void deleteEmployeePhone(long id) {
employeePhoneDao.deleteById(id);
}
@Override
public List<EmployeePhone> findEmployeePhones(long id) {
Employee employee = employeeDao.findById(id).get();
return employee.getEmployeePhones();
}
@Override
public EmployeePhone findEmployeePhone(long id) {
return employeePhoneDao.findById(id).get();
}
}
Here, we are creating a class EmployeeServiceImpl
src/main/java/com/company/impl/EmployeeServiceImpl.java):
package com.company.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.company.dao.DepartmentDao;
import com.company.dao.EmployeeDao;
import com.company.modal.Department;
import com.company.modal.Employee;
import com.company.service.EmployeeService;
@Transactional
@Component
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
@Override
public Employee addEmployee(Employee employee, long id) {
Department department = departmentDao.findById(id).get();
department.addEmployee(employee);
return employeeDao.save(employee);
}
@Override
public Employee editEmployee(Employee employee, long id) {
Employee existEmployee = employeeDao.findById(id).get();
existEmployee.setName(employee.getName());
existEmployee.setAddress(employee.getAddress());
existEmployee.setSalary(employee.getSalary());
existEmployee.setBirthDate(employee.getBirthDate());
existEmployee.setHiringDate(employee.getHiringDate());
return employeeDao.save(existEmployee);
}
@Override
public Employee findEmployee(long id) {
return employeeDao.findById(id).get();
}
@Override
public void deleteEmployee(long id) {
employeeDao.deleteById(id);
}
@Override
public List<Employee> findEmployees() {
return employeeDao.findAll();
}
}
Here, we are creating a class ProjectServiceImpl
src/main/java/com/company/impl/ProjectServiceImpl.java):
package com.company.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.company.dao.DepartmentDao;
import com.company.dao.EmployeeDao;
import com.company.dao.ProjectDao;
import com.company.modal.Department;
import com.company.modal.Employee;
import com.company.modal.Project;
import com.company.service.ProjectService;
@Transactional
@Component
public class ProjectServiceImpl implements ProjectService {
@Autowired
private ProjectDao projectDao;
@Autowired
private DepartmentDao departmentDao;
@Autowired
private EmployeeDao employeeDao;
@Override
public Project addProjectToEmployee(long long idEmployee, long idProject) {
Employee employee = employeeDao.findById(idEmployee).get();
Project project = projectDao.findById(idProject).get();
employee.addProjectToEmploye(project);
return projectDao.save(project);
}
@Override
public Project addProjectToDeprtment(Project project, long id) {
Department department = departmentDao.findById(id).get();
project.setCreateAt(new Date());
department.addProjectToDepratment(project);
return projectDao.save(project);
}
@Override
public Project editProject(Project project, long id) {
Project existProject = projectDao.findById(id).get();
existProject.setName(project.getName());
existProject.setDescription(project.getDescription());
existProject.setProcess(project.getProcess());
return projectDao.save(existProject);
}
@Override
public Project findProject(long id) {
return projectDao.findById(id).get();
}
@Override
public void deleteProejct(long id) {
Project project = projectDao.findById(id).get();
projectDao.delete(project);
}
@Override
public List<Project> findProjectsForEmplopyee(long id) {
Employee employee = employeeDao.findById(id).get();
return employee.getProjects();
}
@Override
public List<Project> findProjects() {
return projectDao.findAll();
}
@Override
public void deleteProjectFromEmployee(long long idEmployee, long long idProject) {
Employee employee = employeeDao.findById(idEmployee).get();
Project project = projectDao.findById(idProject).get();
employee.getProjects().remove(project);
}
}
Here, we are creating a class UserServiceImpl
src/main/java/com/company/impl/UserServiceImpl.java):
package com.company.impl;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.company.dao.UserDao;
import com.company.modal.User;
import com.company.service.UserService;
@Transactional
@Component
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User addUser(User user) {
List<User> users = userDao.findAll();
if (users.size() == 0) {
user.setAdmin(true);
}
for (User existUser : users) {
if (user.getUsername().equals(existUser.getUsername())) {
existUser.setUsername(existUser.getUsername());
existUser.setPassword(existUser.getPassword());
return userDao.save(existUser);
}
}
return userDao.save(user);
}
@Override
public List<User> findAllUsers() {
return userDao.findAll();
}
@Override
public User editUser(User user, long id) {
User existUser = userDao.findById(id).get();
existUser.setUsername(user.getUsername());
existUser.setPassword(user.getPassword());
return userDao.save(existUser);
}
@Override
public User findUserById(long id) {
return userDao.findById(id).get();
}
@Override
public void deleteUser(long id) {
userDao.deleteById(id);
}
@Override
public User findByUsername(String username) {
Optional<User> users = userDao.findByUsername(username);
if (users.isPresent()) {
User user = users.get();
return user;
}
return null;
}
}
@RestController API
@RestController is a convenience annotation for creating Restful controllers. It is a specialization of @Component and is autodetected through classpath scanning. It adds the @Controller and @ResponseBody annotations. It converts the response to JSON or XML. It does not work with the view technology, so the methods cannot return ModelAndView. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation.
We will create these class in controller package:
-> CompanyController
-> DepartmentController
-> EmployeeController
-> EmployeePhoneController
-> ProjectController
-> UserController
Here, we are creating a class CompanyController
src/main/java/com/company/controller/CompanyController.java):
package com.company.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.company.modal.Company;
import com.company.service.CompanyService;
@RestController
@RequestMapping(value = "/api")
@CrossOrigin(origins = "*")
public class CompanyController {
@Autowired
private CompanyService companyService;
@PostMapping("/addCompany/{id}")
Company addCompany( @RequestBodyCompany company, @PathVariable long id) {
return companyService.addCompany(company, id);
}
@PutMapping("/editCompany/{id}")
Company editCompany( @RequestBody Company company, @PathVariable long id) {
return companyService.editCompany(company, id);
}
@GetMapping("/findCompany/{id}")
Company findCompany(@PathVariable long id) {
return companyService.findCompany(id);
}
@DeleteMapping("/deleteCompany/{id}")
void deleteCompany(@PathVariable long id) {
companyService.deleteCompany(id);
}
@GetMapping("/findCompanies")
List<Company> findCompaniesForUser() {
return companyService.findCompanies();
}
}
Here, we are creating a class DepartmentController
src/main/java/com/company/controller/DepartmentController.java):
package com.company.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.company.modal.Department;
import com.company.service.DepartmentService;
@RestController
@RequestMapping(value = "/api")
@CrossOrigin(origins = "*")
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
@PostMapping("/addDepartment/{id}")
Department addDepartment(@RequestBody Department department, @PathVariable long id) {
return departmentService.addDepartment(department, id);
}
@PutMapping("/editDepartment/{id}")
Department editDepartment(@RequestBody Department department, @PathVariable long id) {
return departmentService.editDepartment(department, id);
}
@GetMapping("/findDepartment/{id}")
Department findDepartment(@PathVariable long id) {
return departmentService.findDepartment(id);
}
@DeleteMapping("/deleteDepartment/{id}")
void deleteDepartment(@PathVariable long id) {
departmentService.deleteDepartment(id);
}
}
Here, we are creating a class EmployeeController
src/main/java/com/company/controller/EmployeeController.java):
package com.company.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.company.modal.Employee;
import com.company.service.EmployeeService;
@RestController
@RequestMapping(value = "/api")
@CrossOrigin(origins = "*")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/addEmployee/{id}")
Employee addEmployee(@RequestBody Employee employee, @PathVariable long id) {
return employeeService.addEmployee(employee, id);
}
@PutMapping("/editEmployee/{id}")
Employee editEmployee(@RequestBody Employee employee, @PathVariable long id) {
return employeeService.editEmployee(employee, id);
}
@GetMapping("/findEmployee/{id}")
Employee findEmployee(@PathVariable long id) {
return employeeService.findEmployee(id);
}
@DeleteMapping("/deleteEmployee/{id}")
void deleteEmployee(@PathVariable long id) {
employeeService.deleteEmployee(id);
}
@GetMapping("/findEmployees")
List<Employee> findEmployees() {
return employeeService.findEmployees();
}
}
Here, we are creating a class EmployeePhoneController
src/main/java/com/company/controller/EmployeePhoneController.java):
package com.company.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.company.modal.EmployeePhone;
import com.company.service.EmployeePhoneService;
@RestController
@RequestMapping(value = "/api")
@CrossOrigin(origins = "*")
public class EmployeePhoneController {
@Autowired
private EmployeePhoneService employeePhoneService;
@PostMapping("/addEmployeePhone/{id}")
EmployeePhone addEmployeePhone(@RequestBody EmployeePhone employeePhone, @PathVariable long id) {
return employeePhoneService.addEmployeePhone(employeePhone, id);
}
@PutMapping("/editEmployeePhone/{id}")
EmployeePhone editEmployeePhone(@RequestBody EmployeePhone employeePhone, @PathVariable long id) {
return employeePhoneService.editEmployeePhone(employeePhone, id);
}
@DeleteMapping("/deleteEmployeePhone/{id}")
void deleteEmployeePhone(@PathVariable long id) {
employeePhoneService.deleteEmployeePhone(id);
}
@GetMapping("/findEmployeePhones/{id}")
List<EmployeePhone> findEmployeePhones(@PathVariable long id) {
return employeePhoneService.findEmployeePhones(id);
}
@GetMapping("/findEmployeePhone/{id}")
EmployeePhone findEmployeePhone(@PathVariable long id) {
return employeePhoneService.findEmployeePhone(id);
}
}
Here, we are creating a class ProjectController
src/main/java/com/company/controller/ProjectController.java):
package com.company.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.company.modal.Project;
import com.company.service.ProjectService;
@RestController
@RequestMapping(value = "/api")
@CrossOrigin(origins = "*")
public class ProjectController {
@Autowired
private ProjectService projectService;
@PostMapping("/addProjectToEmployee/{idEmployee}/{idProject}")
Project addProjectToEmploye(@PathVariable long idEmployee, @PathVariable long idProject) {
return projectService.addProjectToEmployee(idEmployee, idProject);
}
@PostMapping("/addProjectToDeprtment/{id}")
Project addProjectToDeprtment(@RequestBody Project project, @PathVariable long id) {
return projectService.addProjectToDeprtment(project, id);
}
@PutMapping("/editProject/{id}")
Project editProject(@RequestBody Project project, @PathVariable long id) {
return projectService.editProject(project, id);
}
@GetMapping("/findProject/{id}")
Project findProject(@PathVariable long id) {
return projectService.findProject(id);
}
@DeleteMapping("/deleteProejct/{id}")
void deleteProejct(@PathVariable long id) {
projectService.deleteProejct(id);
}
@GetMapping("/findProjectsForEmplopyee/{id}")
List<Project> findProjectsForEmplopyee(@PathVariable long id) {
return projectService.findProjectsForEmplopyee(id);
}
@GetMapping("/findProjects")
List<Project> findProjects() {
return projectService.findProjects();
}
@DeleteMapping("/deleteProjectFromEmployee/{idEmployee}/{idProject}")
void deleteProjectFromEmployee(@PathVariable long idEmployee, @PathVariable long idProject) {
projectService.deleteProjectFromEmployee(idEmployee, idProject);
}
}
Here, we are creating a class UserController
src/main/java/com/company/controller/UserController.java):
package com.company.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.company.modal.User;
import com.company.service.UserService;
@RestController
@RequestMapping(value = "/api")
@CrossOrigin(origins = "*")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/addUser")
User addUser(@RequestBody User user) {
return userService.addUser(user);
}
@GetMapping("/findAllUsers")
List<User> findAllUsers() {
return userService.findAllUsers();
}
@PutMapping("/editUser/{id}")
User editUser(@RequestBody User user, @PathVariable long id) {
return userService.editUser(user, id);
}
@GetMapping("/findUserById/{id}")
User findUserById(@PathVariable long id) {
return userService.findUserById(id);
}
@DeleteMapping("/deleteUser/{id}")
void deleteUser(@PathVariable long id) {
userService.deleteUser(id);
}
@GetMapping("/findByUsername/{username}")
User findByUsername(@PathVariable String username) {
return userService.findByUsername(username);
}
}
CompanyApplication
@BookStoreApplication and its use in a simple Spring Boot application. We use the @SpringBootApplication annotation in our Application or Main class to enable a host of features, e.g. Java-based Spring configuration, component scanning, and in particular for enabling Spring
src/main/java/com/company/CompanyApplication.java):
package com.company;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CompanyApplication {
public static void main(String[] args) {
SpringApplication.run(CompanyApplication.class, args);
System.out.println("App started....");
}
}
Conclusion
Now we have an overview of Spring Boot example when building a @RestController API.
We also take a look at client-server architecture for REST API using Spring Web MVC & Spring Data JPA, as well, we are gooing to continue with Angular project structure for building a front-end app to make HTTP requests and consume responses.