Search Tutorials


E-commerce Website - Online Book Store - Create Book Admin Module - Part 1 | JavaInUse
     
 

   
   

E-commerce Website - Online Book Store - Create Book Admin Module - Part 1

In this tutorial series we will be developing an E-commerce website for buying books. In a previous tutorial we created the user admin module. In this tutorial we will be adding a book admin component. Using this component we will be able to add new book and delete existing books. In this tutorial we will be listing existing books using the books admin module. This will be similar to the listing of existing users in functionality that we had implemented before.

E-commerce Website - Online Book Store using Angular 8 + Spring Boot

E-commerce Website - Online Book Store using Angular 8 + Spring Boot Introduction E-commerce Website - Online Book Store - Create Menu Module E-commerce Website - Online Book Store - Create User Admin Module - Part 1 E-commerce Website - Online Book Store - Create User Admin Module - Part 2 E-commerce Website - Online Book Store - Create User Admin Module - Part 3 E-commerce Website - Online Book Store - Create Book Admin Module - Part 1 E-commerce Website - Online Book Store - Create Book Admin Module - Part 2 E-commerce Website - Online Book Store - Create Book Admin Module - Part 3 E-commerce Website - Online Book Store - Create Book Admin Module - Part 4 Ecommerce Website - Online Book Store - Create Book Shopping Module

Video

This tutorial is explained in the below Youtube Video.

Spring Boot Application

We will be modifying the Spring Boot Application we created in previous tutorial to expose a REST end point to return a list of books.
Create the Book model class with the jpa annotations for mapping java object to database table. We will be creating a table named book for storing book details.
package com.javainuse.model;

import javax.persistence.*;

@Entity
@Table(name = "book")
public class Book {

	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Column(name = "name")
	private String name;

	@Column(name = "author")
	private String author;
	
	@Column(name = "price")
	private String price;

	@Column(name = "picByte", length = 1000)
	private byte[] picByte;

	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 getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getPrice() {
		return price;
	}

	public void setPrice(String price) {
		this.price = price;
	}

	public byte[] getPicByte() {
		return picByte;
	}

	public void setPicByte(byte[] picByte) {
		this.picByte = picByte;
	}
}

Create the repository class by extending the JpaRepository. By extending JpaRepository we get a bunch of generic CRUD methods into our type that allows saving Books, deleting and retrieving.
package com.javainuse.db;

import org.springframework.data.jpa.repository.JpaRepository;

import com.javainuse.model.Book;

public interface BookRepository extends JpaRepository<Book, Long> {
}
@RequestMapping maps /get request to return a list of books. Also here we are using CrossOrigin annotation to specify that calls will be made to this controller from different domains. In our case we have specified that a call can be made from localhost:4200.
package com.javainuse.controller;

import java.io.IOException;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.javainuse.db.BookRepository;
import com.javainuse.model.Book;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(path = "books")
public class BookController {

	@Autowired
	private BookRepository bookRepository;
	
	@GetMapping("/get")
	public List<Book> getBooks() {
		return bookRepository.findAll();
	}
}
Compile and the run the SpringBootHelloWorldApplication.java as a Java application.
Go to localhost:8080/books/get

Currently no records are present in users table. Insert a record in book table and again make the REST call
insert into book(id,name,author,price)values(1,'book1','author1',10);


Go to localhost:8080/users/get

Angular Code

We will be modifying the angular code we had developed in the previous tutorial. The page Structure for the Book-Admin Page is as follows-

We will be displaying the list of existing books. We can then select an existing book to view details. Also we will be able to add/edit a book.
We will be having 3 Book Admin components-
  • Books Component - List the existing books.
  • Book Detail Component - Select existing book to get the book details. Using this component we can also delete the existing book
  • Add/Edit Book Component - Add new book/Edit existing book
In this tutorial we will be creating the Books Component to list the existing Books. In the next tutorials we will be developing the Book Detail and Add/Edit Book Component.
Create a component named books as follows-    
ng generate component admin/books





This component will fetch the existing books from the backend and display it. In the beginning we will be mocking the book list. Later we will fetch it from the backend.
Create a class named Book  
  export class Book {
    id: number;
    name: string;
    author: string;
    price: number;
    picByte: string;    
    }
In the books component create an array of type Book. We will be initializing this book list in the ngOnInit method of the book component.
import { Component, OnInit } from '@angular/core';
import { Book } from '../../model/Book';

@Component({
  selector: 'app-books',
  templateUrl: './books.component.html',
  styleUrls: ['./books.component.css']
})
export class BooksComponent implements OnInit {

  books: Array<Book>;

  constructor() { }

  ngOnInit() {

    this.books = new Array<Book>();

    const book1 = new Book();
    book1.id = 1;
    book1.name = 'book1';
    book1.author = 'author1';
    book1.price = 5;

    const book2 = new Book();
    book2.id = 2;
    book2.name = 'book2';
    book2.author = 'author2';
    book2.price = 15;

    this.books.push(book1);
    this.books.push(book2);
  }

}
Modify the book component html to display the books list.
<h1>Books Admin</h1>

<div class="container row">
  <div class="col-md-6">
    <table class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>Book Name</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let book of books">
          <td>{{book.id}}</td>
          <td>{{book.name}}</td>
          <td>
            <button type="button" class="btn btn-primary" (click)="setBook(book.id)">Show Details</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
  <div class="col-md-6">
    View Book Details/Add Book
  </div>
</div>
Next we will be modifying the app-routing module file to define the route for the book component-
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UsersComponent } from './admin/users/users.component';
import { BooksComponent } from './admin/books/books.component';

const routes: Routes = [
  { path: 'admin/users', component: UsersComponent },
  { path: 'admin/books', component: BooksComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Start the application and go to localhost:4200/admin/books

We will now be making changes so that the application gets the list of books from the mysql database using Spring Boot. We will be modifying the http-client.service.ts file. We will be creating a method which makes call to the spring boot application using the defined httpClient.    
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../model/User';
import { Book } from '../model/Book';


@Injectable({
  providedIn: 'root'
})
export class HttpClientService {

  constructor(private httpClient: HttpClient) {
  }

  getUsers() {
    return this.httpClient.get<User[]>('http://localhost:8080/users/get');
  }

  addUser(newUser: User) {
    return this.httpClient.post<User>('http://localhost:8080/users/add', newUser);
  }

  deleteUser(id) {
    return this.httpClient.delete<User>('http://localhost:8080/users/' + id);
  }

  getBooks() {
    return this.httpClient.get<Book[]>('http://localhost:8080/books/get');
  }
}
Next using constructor dependency injection we will be providing the BooksComponent an instance of HttpClientService.  Using this service we make a call to spring boot application to get a list of books.
import { Component, OnInit } from '@angular/core';
import { Book } from '../../model/Book';
import { HttpClientService } from '../../service/http-client.service';

@Component({
  selector: 'app-books',
  templateUrl: './books.component.html',
  styleUrls: ['./books.component.css']
})
export class BooksComponent implements OnInit {

  books: Array<Book>;

  constructor(private httpClientService: HttpClientService) { }

  ngOnInit() {
   this.httpClientService.getBooks().subscribe(
      response => this.handleSuccessfulResponse(response)
    );
  }

  handleSuccessfulResponse(response) {
    this.books = response;
  }
}
Start the Spring Boot Application and also the Angular application. Go to localhost:4200/admin/books  

Next we will be adding the admin/users link in the menu. Modify the menu.html as follows-
<header>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark">
        <div><a href="https://www.javainuse.com" class="navbar-brand">JavaInUse</a></div>

        <ul class="navbar-nav">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
                    aria-haspopup="true" aria-expanded="false">
                    Admin
                </a>
                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <a routerLink="/admin/users" class="dropdown-item">Users</a>
                    <a routerLink="/admin/books" class="dropdown-item">Books</a>
                </div>
            </li>
        </ul>
    </nav>
</header>


Download Source Code

Download it -
Spring Boot + E-commerce
Angular8 Online Book Store

 

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions