Skip to main content

Spring Boot-Angular-Bootstrap-JPA-CRUD

In this article, we will show you how to develop a Spring Boot CRUD  application with, Angular, embedded Tomcat and JPA
Following technologies stack being used:
  • Spring Boot 2.1.4.RELEASE
  • Spring 5.1.6.RELEASE 
  • Angular JS
  • JDK 1.8
  • Eclipse Oxygen
  • Bootstrap
  • Thymeleaf
  • H2DB -in-memory database
User Interface
Project Structure


Pom.xml(maven)
<?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 http://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.1.4.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>
 <artifactId>springboot-jpa-Angular-bootstrap-CRUD</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>springboot-jpa-Angular-bootstrap-CRUD</name>
 <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-thymeleaf</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>
  </dependency>
  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
  <dependency>
   <groupId>javax.validation</groupId>
   <artifactId>validation-api</artifactId>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>
 <groupId>com.knowledgefactory</groupId>
 <description>springboot-jpa-Angular-bootstrap-CRUD</description>
</project>
WebController
package com.knowledgefactory.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.ui.Model;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.knowledgefactory.entity.User;
import com.knowledgefactory.exception.RecordNotFoundException;
import com.knowledgefactory.service.UserService;
@RestController
public class WebController {
 @Autowired
 UserService service;
 @GetMapping({ "/getAllUsers" })
 public ResponseEntity<List<User>> getAllUsers() {
  List<User> list = service.getAllusers();
  return new ResponseEntity<List<User>>(list, HttpStatus.OK);
 }
 @DeleteMapping(path = "/delete/{id}")
 public void deleteUserById(Model model, @PathVariable("id") Long id) throws RecordNotFoundException {
  service.deleteUserById(id);
 }
 @PostMapping(path = "/createUser")
 public User createOrUpdateUser(@RequestBody User user) {
  return service.createOrUpdateUser(user);
 }
}
Main Controller
package com.knowledgefactory.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
 @RequestMapping("/")
 public String welcome() {
  return "index";
 }
}
User(Entity Class)
package com.knowledgefactory.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 @Column(name = "first_name")
 private String firstName;
 @Column(name = "last_name")
 private String lastName;
  @Column(name = "email", nullable = false, length = 200)
 private String email;
 public User() {
  super();
 }
 public Long getId() {
  return id;
 }
 public void setId(Long 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;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public User(String firstName, String lastName, String email) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
 }
 @Override
 public String toString() {
  return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
 }
}
UserRepository
package com.knowledgefactory.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.knowledgefactory.entity.User;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {

}
UserService
package com.knowledgefactory.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.knowledgefactory.entity.User;
import com.knowledgefactory.exception.RecordNotFoundException;
import com.knowledgefactory.repository.UserRepository;
@Service
public class UserService {
 @Autowired
 UserRepository repository;
 public List<User> getAllusers() {
  List<User> result = (List<User>) repository.findAll();
  if (result.size() > 0) {
   return result;
  } else {
    return new ArrayList<User>();
  }
 }
 public User getUserById(Long id) throws RecordNotFoundException {
  Optional<User> user = repository.findById(id);
  if (user.isPresent()) {
   return user.get();
  } else {
   throw new RecordNotFoundException("No user record exist for given id");
  }
 }
 public User createOrUpdateUser(User entity) {
  if (entity.getId() == null) {
   entity = repository.save(entity);
   return entity;
  } else {
   Optional<User> user = repository.findById(entity.getId());
   if (user.isPresent()) {
    User newEntity = user.get();
    newEntity.setEmail(entity.getEmail());
    newEntity.setFirstName(entity.getFirstName());
    newEntity.setLastName(entity.getLastName());
    newEntity = repository.save(newEntity);
    return newEntity;
   } else {
    entity = repository.save(entity);
    return entity;
   }
  }
 }
 public void deleteUserById(Long id) throws RecordNotFoundException {
  Optional<User> user = repository.findById(id);
  if (user.isPresent()) {
   repository.deleteById(id);
  } else {
   throw new RecordNotFoundException("No user record exist for given id");
  }
 }
}
Spring Boot(Main Class)
package com.knowledgefactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.knowledgefactory.entity.User;
import com.knowledgefactory.repository.UserRepository;
@SpringBootApplication
public class KnowledgefactorydemoApplication implements CommandLineRunner {
 @Autowired
 private UserRepository repository;
 public static void main(String[] args) {
  SpringApplication.run(KnowledgefactorydemoApplication.class, args);
 }
 @Override
 public void run(String... args) throws Exception {
  repository.save(new User("sibin", "knf", "sibinraziya@gmail.com"));
  repository.save(new User("knf", "springboot", "sibinraziya@gmail.com"));
 }}
main.js
var app = angular.module("UserManagement", []);
// Controller Part
app.controller("UserController", function($scope, $http) {
  $scope.users = [];
 $scope.userForm = {
  id : "",
  firstName : "",
  lastName : "",
  email : ""
 };
  // Now load the data from server
 _refreshUserData();
  $scope.submitUser = function() {
   var method = "";
  var url = "";
   method = "POST";
  url = '/createUser';
   $http({
   method : method,
   url : url,
   data : angular.toJson($scope.userForm),
   headers : {
    'Content-Type' : 'application/json'
   }
  }).then(_success, _error);
 };
  $scope.createUser = function() {
  _clearFormData();
 }
  $scope.deleteUser = function(user) {
  $http({
   method : 'DELETE',
   url : '/delete/' + user.id
  }).then(_success, _error);
 };
  // In case of edit
 $scope.editUser = function(user) {
  $scope.userForm.id = user.id;
  $scope.userForm.firstName = user.firstName;
  $scope.userForm.lastName = user.lastName;
  $scope.userForm.email = user.email;
 };
  function _refreshUserData() {
  $http({
   method : 'GET',
   url : '/getAllUsers'
  }).then(function(res) { // success
   $scope.users = res.data;
  }, function(res) { // error
   console.log("Error: " + res.status + " : " + res.data);
  });
 }
  function _success(res) {
  _refreshUserData();
  _clearFormData();
 }
  function _error(res) {
  var data = res.data;
  var status = res.status;
  var header = res.header;
  var config = res.config;
  alert("Error: " + status + ":" + data);
 }
  // Clear the form
 function _clearFormData() {
  $scope.userForm.id = -1;
  $scope.userForm.firstName = "";
  $scope.userForm.lastName = ""
  $scope.userForm.email = ""
 }
 ;
});
index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot-Angular</title>
<script th:src="@{/angular.js}"></script>
<script th:src="@{/jquery.min.js}"></script>
<script th:src="@{/bootstrap.min.js}"></script>
<script th:src="@{/main.js}"></script>
<link rel="stylesheet" type="text/css" media="all"
 href="../../bootstrap.min.css" th:href="@{/bootstrap.min.css}" />
<head>
<body ng-app="UserManagement" ng-controller="UserController">
 <div class="container">
  <div class="row">
   <div class="col-sm-2"></div>
  <div class="col-sm-8">
    <h3>CRUD: Spring Boot +AngularJS+Bootstrap</h3>
    <form ng-submit="submitUser()">
     <table class="table table-striped">
      <tr>
       <td>First Name</td>
       <td><input class="form-control input-sm" type="text"
        ng-model="userForm.firstName" /></td>
      </tr>
      <tr>
       <td>Last Name</td>
       <td><input type="text" class="form-control input-sm"
        ng-model="userForm.lastName" /></td>
      </tr>
      <tr>
       <td>Email</td>
       <td><input type="text" class="form-control input-sm"
        ng-model="userForm.email" /></td>
      </tr>
      <tr>
       <td colspan="2"><input type="submit" value="Submit"
        class="btn btn-primary" /></td>
      </tr>
     </table>
    </form>
    <br /> <a class="create-button" ng-click="createUser()"><button
      type="button" class="btn btn-info">Create User</button></a><br>
    <br>
    <table class="table table-striped">
     <tr>
      <th>Id</th>
      <th>FirstName</th>
      <th>LastName</th>
      <th>Email</th>
      <th>Edit</th>
      <th>Delete</th>
     </tr>
     <!-- $scope.users -->
     <tr ng-repeat="user in users">
      <td>{{ user.id }}</td>
      <td>{{ user.firstName }}</td>
      <td>{{ user.lastName }}</td>
      <td>{{ user.email }}</td>
      <td><a ng-click="editUser(user)" class="btn btn-warning">Edit</a></td>
      <td><a ng-click="deleteUser(user)" class="btn btn-danger">Delete</a>
      </td>
     </tr>
    </table>
   </div>
   <div class="col-sm-2"></div>
  </div>
 </div>
</body>
</html>

Run
$ mvn spring-boot:run

Comments

Post a Comment

Popular posts from this blog

Spring boot video streaming example-HTML5

This article shows you how to stream MP4 video in Spring Boot web application 
User Interface

Project Structure

Home Controller
@Controller
public class HomeController {
 @Autowired
 private MyResourceHttpRequestHandler handler;
 private final static File MP4_FILE = new File("D:\\videofiles\\video1.mp4");
 // supports byte-range requests
 @GetMapping("/index")
 public String home() {
  return "index";
 }
 // supports byte-range requests
 @GetMapping("/byterange")
 public void byterange( HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setAttribute(MyResourceHttpRequestHandler.ATTR_FILE, MP4_FILE);
  handler.handleRequest(request, response);
 }}
Spring Boot 
@SpringBootApplication
@ComponentScan({ "com" })
public class KnowledgefactorydemoApplication {
 public static void main(String[] args) {
  SpringApplication.run(KnowledgefactorydemoApplication.class, args);
 }}
MyResource HttpRequestHandler
@Componen…

DataTable-Pagination example with Spring boot,jQuery and ajax free download

This article shows you DataTable-Pagination example with Spring boot, jQuery and ajax. 

Following technologies stack being used:
Spring Boot 2.1.1.RELEASESpring 5.1.3.RELEASE Maven 3DatatablejQueryFree Markerjavascriptajax Project Structure
View(index.ftl) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Knf|Pagination-Datatables</title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../../css/jquery.dataTables.min.css"> <body>  <section class="content">   <div class="container-fluid">    <table id="example" class="display" style="width: 100%">     <thead>      <tr>       <th>First name</th>       <th>La…

9 Best Job Posting Sites for Employee 2020-2022

One of the most common ways today’s job seekers uncover employment opportunities are by using online sources. There are hundreds of job boards, both generic and niche, as well as aggregators, social media channels, networking groups, and staffing company websites to choose from. The good news is they provide plenty of listings. The bad news is you can be easily overwhelmed by so many options. Here, knowledge factory offers 9 of what is generally considered the best job search websites around. There are many others, of course, but this list of best job search websites should give you a good starting point for your next job hunt: 1. LinkedIn
This top networking site allows you to find jobs through your extended network. User profiles serve as resumes. You can easily share career-related content and solicit or supply recommendations. Additionally, you can join groups, participate in conversations, and follow companies you find interesting and relevant to your job search. Premium pai…