Building a Web Application with Spring Boot, Angular and JPA

Hello folks! In this tutorial we are going to develop a web application with Spring Boot, Angular and JPA and perform CRUD operation on it. I am dividing this tutorial into two parts: in first part we’re going to develop back-end with Spring Boot and JPA, and in the second part we’re going to build simple front-end with Angular technology. By the end of the tutorial we are going to build something like this:

Web Application with Spring Boot, Angular and JPA Home Page
Web Application with Spring Boot, Angular and JPA edit page
Web Application with Spring Boot, Angular and JPA add page

The code for the whole project can be found on my Github account.

Before beginning this tutorial, I guess you have some background with JPA, Spring Boot and Angular. If not, then don’t worry folks, you can simply check out this simple tutorials: Spring Boot Getting Started and Angular Getting Started.

Web Application with Spring Boot, Angular and JPA

Lets start folks.

Open Spring Tool Suite (you can use your any favorite IDE), and create a Spring Boot App named SpringBootJPA, package named com.sukuldhoka.demo and don’t forget to include Web, JPA and My-SQL dependencies, as we’ve done before. I’m using SQLYog Database for storing our data, and if you’ve not already installed it, you can download it from here and configure it. Then create database named “sukuldhoka“.

Inside src/main/resources, you’ll find application.properties where you can put your configuration for your application. For our app, put the following in application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/sukuldhoka
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto = update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

Hurrah!!! Now we don’t have to further deal with database for our application, but make sure that you’ve set the above values properly. That’s the beauty of Spring Boot Application. 🙂 🙂

Now, let’s write some code:

Create a package named com.sukuldhoka.model and create two model classes Employee.java and Role.java and paste the following codes.

package com.sukuldhoka.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;


@Entity
@Table(name="employee")
public class Employee {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Long id;
	
	private String empName;
	private String empAddress;
	private int empAge;
	
	@ManyToOne(optional=false)
	@JoinColumn(name="roles_id", referencedColumnName="id")
	private Role role;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public String getEmpAddress() {
		return empAddress;
	}
	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;
	}
	public int getEmpAge() {
		return empAge;
	}
	public void setEmpAge(int empAge) {
		this.empAge = empAge;
	}
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}
	
}
package com.sukuldhoka.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="role")
public class Role {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	private String roleName;
	private String roleDesc;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public String getRoleDesc() {
		return roleDesc;
	}
	public void setRoleDesc(String roleDesc) {
		this.roleDesc = roleDesc;
	}
	
	
}

The above classes are based on JPA and I’ve already discussed about JPA in my previous tutorials. Here, @Entity annotation will automatically creates table for you in database sukuldhoka. Remember the days, when you used JDBC connections and other SQL Queries, yuck !!!

After this, create a package named com.sukuldhoka.dao and create two interfaces named EmployeeRepo.java and RoleRepo.java. Here, paste the following code:

package com.sukuldhoka.dao;

import org.springframework.data.repository.CrudRepository;

import com.sukuldhoka.model.Employee;

public interface EmployeeRepo extends CrudRepository<Employee, Long> {
	public Employee findByEmpName(String name);
}
package com.sukuldhoka.dao;

import org.springframework.data.repository.CrudRepository;

import com.sukuldhoka.model.Role;

public interface RoleRepo extends CrudRepository<Role, Long>{

}

Now, you might think what the shit is happening. But cheers guys, this is another beauty of spring framework resembled by spring boot. Here we are just inheriting the CrudRepository<T, ID> interface provided by Spring where the first parameter T is entity class name and second parameter ID is data-type of the primary key of corresponding entity class.

Now with this implementation, you don’t have to write hard code for CRUD operation; you can just enjoy its methods. Note that in EmployeeRepo.class, we’ve written a method findByEmpName(String name) but guess what, we don’t have to define it. That method is also based on spring naming convention, where we’re using findBy+ “{any object in entity class}”, and in our case we do have empName in Employee.class.

Isn’t it cool?? Obviously!!

Now create a package com.sukuldhoka.service, then create a class EmployeeService.java and insert the following code:

package com.sukuldhoka.service;

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

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

import com.sukuldhoka.dao.EmployeeRepo;
import com.sukuldhoka.dao.RoleRepo;
import com.sukuldhoka.model.Employee;
import com.sukuldhoka.model.Role;

@Component
public class EmployeeService {

	@Autowired
	private EmployeeRepo employeeRepo;
	
	@Autowired
	private RoleRepo roleRepo;
	
	public List<Employee> getAllEmployee() {
		return (List<Employee>)	employeeRepo.findAll();
	}
	
	public void addEmployee(Employee employee) {
		employeeRepo.save(employee);
	}
	
	public Optional<Employee> getSingleEmployee(Long id) {
		return employeeRepo.findById(id);
	}
	
	public void updateEmployee(Long id, Employee employee) {
		employeeRepo.save(employee);
	}
	
	public void deleteEmployee(Long id) {
		employeeRepo.deleteById(id);
	}
	
	public Employee findByEmployeeName(String name) {
		return employeeRepo.findByEmpName(name);
	}
	
	public List<Role> getAllRole() {
			return (List<Role>) roleRepo.findAll();
	}
}

Here see the annotation @Component and @Autowired. These are spring annotations; @Component shows that the class is service class going to be called by @Controller class for performing business logic and @Autowired is used for dependency injection.

After that, create a package named com.sukuldhoka.controller where we are going to add EmployeeController.class and include the following code:

package com.sukuldhoka.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sukuldhoka.model.Employee;
import com.sukuldhoka.model.Role;
import com.sukuldhoka.service.EmployeeService;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class EmployeeController {

	@Autowired
	EmployeeService employeeService;
	
	@RequestMapping("/employees")
	public List<Employee> getEmployee() {
		return (List<Employee>) employeeService.getAllEmployee();
		 
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/employees")
	public void addEmployee(@RequestBody Employee employee) {
		employeeService.addEmployee(employee);
	}
	
	@RequestMapping("/employees/{id}")
	public Optional<Employee> getSingleEmployee(@PathVariable Long id) {
		return employeeService.getSingleEmployee(id);
	}
	
	@RequestMapping(method=RequestMethod.PUT, value="/employees/{id}")
	public void updateEmployee(@RequestBody Employee employee, @PathVariable Long id) {
		employeeService.updateEmployee(id, employee);
	}
	
	@RequestMapping(method=RequestMethod.DELETE, value="/employees/{id}")
	public void deleteEmployee(@PathVariable Long id) {
		employeeService.deleteEmployee(id);
	}
	
	@RequestMapping("/employees/name/{name}")
	public Employee findByEmpName(@PathVariable String name) {
		return employeeService.findByEmployeeName(name);
	}
	
	@RequestMapping("/employees/role")
	public List<Role> getRoles() {
		return (List<Role>) employeeService.getAllRole();
	}
 	

}

Here we are using @RestController as we are going to provide REST API. We’re also using @CrossOrigin so that we can test this API through front end running on this same computer.

Finally, add some annotations on SpringBootJpaApplication.class located in com.sukuldhoka.demo package and it will look like:

package com.sukuldhoka.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan("com.sukuldhoka")
@EntityScan("com.sukuldhoka.model")
@EnableJpaRepositories("com.sukuldhoka.dao")
public class SpringBootJpaApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootJpaApplication.class, args);
	}

}

Finally you are done with the back-end. You can test this API using Postman and I’ve already explained how to use postman in one of my previous tutorials. If you run the application, we can see the output as:

Web Application with Spring Boot, Angular and JPA

I’ve manually put some data into database for displaying purpose.

Now we can move toward building front-end, which is very easy if you’ve some basic concept of Angular. So let’s see this in second part.