SpringBoot React DynamoDB CRUD Example

springboot react crud dynamodb

Tutorial: SpringBoot React DynamoDB – Build CRUD Application with SpringBoot React.js Example

In the tutorial, I introduce how to build an “SpringBoot React.js CRUD DynamoDB Example” project with the help of SpringData JPA for POST/GET/PUT/DELETE requests with step by step coding examples:

– SpringBoot project produces CRUD RestAPIs with DynamoDB database using the supporting of Spring Data JPA.
– React.js project will consume the SpringBoot CRUD RestAPIs by Ajax then show up on Reactjs component’s views.

Related posts:


– I draw a fullstack overview Diagram Architecture from React.js Frontend to DynamoDB database through SpringBoot RestAPI backend.
– Develop SpringBoot CRUD RestAPIs with the supporting of SpringWeb Framework.
– Implement Reactjs CRUD application with Ajax fetching APIs to do CRUD request (Post/Get/Put/Delete) to SpringBoot Backend APIs.
– I create a testsuite with a number of integrative testcases with CRUD RestAPI requests from Reactjs to do CRUD requests to SpringBoot RestAPIs Server and save/retrieve data to DynamoDB database.

What will we do?


Overview Diagram Architecture – SpringBoot React DynamoDB (SpringBoot Reactjs CRUD Example)

Overall Architecture System: Reactjs + SpringBoot + DynamoDB

React.js-SpringBoot-DynamoDB-Diagram-Architecture
React.js-SpringBoot-DynamoDB-Diagram-Architecture
  • We build a backend: SpringBoot CRUD Application with DynamoDB that provides RestAPIs for POST/GET/PUT/DELETE data entities and store them in DynamoDB database.
  • We implement React.js CRUD Application that use Ajax to interact (call/receive requests) with SpringBoot CRUD application and display corresponding data in Reactjs Component.

SpringBoot DynamoDB CRUD Design Application

SpringBoot-DynamoDB-CRUD-RestAPI-Fullstack-Diagram-Architecture
SpringBoot-DynamoDB-CRUD-RestAPI-Fullstack-Diagram-Architecture

I build a SpringBoot project that handle all Post/Get/Put/Delete requests from RestClient and do CRUD operations to DynamoDB database to save/retrieve/update and delete entity from DynamoDB and returns back to Restclient the corresponding messages.

We build a SpringBoot project with 2 layers:
– SpringJPA Repository is used to interact with DynamoDB database by a set of CRUD operations.
– RestController layer is a web layer for SpringBoot project, it will directly handle all incomming requests and do the corressponding responses to the calling client.

Reactjs CRUD Application Design

Reactjs CRUD RestAPI Application Frontend Architecture Diagram
Reactjs CRUD RestAPI Application Frontend Architecture Diagram

– Reactjs CRUD Application is designed with 2 main layers:

  • React.js components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
  • Ajax is used by Reactjs component to fetch (post/put/get/delete) data from remote restapi by http request

Reactjs CRUD Application defines 5 components:

  • Home.js is used serve as the landing page for your app.
  • AppNavbar.js is used to establish a common UI feature between components.
  • CustomerList.js is used to show all customers in the web-page
  • CustomerEdit.js is used to modify the existed customer
  • App.js uses React Router to navigate between components.

Integrative Project Goal – SpringBoot React DynamoDB CRUD

Reactjs Home page:

SpringBoot React DynamoDB CRUD - Project Goal - Home Page
Project Goal – Home Page

Reactjs add data:

SpringBoot React DynamoDB CRUD - Project Goal - Add a Customer
Project Goal – Add a Customer

Reactjs List all data:

SpringBoot React DynamoDB CRUD - Project Goal - Customer List
Project Goal – Customer List

Reactjs update data:

Project Goal - Update Customer
Project Goal – Update Customer

Reactjs delete data:

-> Delete a customer Adam with id=2, after successfully, check the customer list again:

Project Goal - List Customer after Delete successfully
Project Goal – List Customer after Delete successfully

How to Integrate Reactjs with SpringBoot?

For starting to integrate Reactjs with SpringBoot project, I recommend you a previous post with detail steps to pratice:

How to Integrate Reactjs with SpringBoot Tutorial

React project structure
React project structure
SpringBoot integrate with Reactjs Production Build
SpringBoot integrate with Reactjs Production Build
SpringBoot Get RestAPI
SpringBoot Get RestAPI

SpringBoot DynamoDB CRUD RestAPIs Example – Backend Development

Now it’s time for building the “SpringBoot DynamoDB CRUD RestAPIs Example” project with a set of simple steps:

  • Create SpringBoot project
  • Configure DynamoDB Database
  • Define SpringData JPA Entity Model
  • Define SpringBoot JPA Repository
  • Implement SpringBoot Controller CRUD RestAPIs

Let’s go!

How to build SpringBoot DynamoDB CRUD RestAPI project

Create SpringBoot DynamoDB project

We use SpringToolSuite to create a simple SpringBoot project with below structure:

SpringBoot project structure
SpringBoot project structure
  • application.properties is used to add the SpringBoot application’s configurations such as: database configuration (MongoDB, DynamoDB, DynamoDB), threadpool, Hibernate, JPA …
  • repository package is used to define a SpringBoot JPA repository to do CRUD operations with DynamoDB
  • controller package is used to implement a SpringBoot RestAPI controller to handle all incomming requests (post/get/put/delete) and response to rest-client.
  • model package is used to define a JPA entity model that maps with the record’s format in DynamoDB database

For handling the web-request and doing CRUD operations with DynamoDB database, we need the supporting of 3 SpringBoot dependencies: spring-boot-starter-web and spring-boot-starter-data-jpa, DynamoDB. So adding it to pom.xml file:

<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>
	<artifactId>aws-java-sdk-postgresql</artifactId>
		<groupId>com.amazonaws</groupId>
	<version>1.11.34</version>
</dependency>

<dependency>
	<groupId>com.github.derjust</groupId>
	<artifactId>spring-data-postgresql</artifactId>
	<version>4.5.0</version>
</dependency>

SpringBoot Configure DynamoDB Database

To initialize a connection with DynamoDB, we open the file application.properties and add below configuration:

SpringBoot helps us to create a datasource by simple configuration in application.properties file. We use the spring.datasource.* to setup the url, username and password for Spring datasource bean as above.

Open application.properties:


amazon.dynamodb.endpoint=http://localhost:8000/
amazon.aws.accesskey=jsa
amazon.aws.secretkey=javasampleapproach

Under package config, create DynamoDBConfig class:


package com.javasampleapproach.dynamodb.config;

import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.util.StringUtils;

@Configuration
@EnableDynamoDBRepositories(basePackages = "com.javasampleapproach.dynamodb.repo")
public class DynamoDBConfig {

	@Value("${amazon.dynamodb.endpoint}")
	private String dBEndpoint;

	@Value("${amazon.aws.accesskey}")
	private String accessKey;

	@Value("${amazon.aws.secretkey}")
	private String secretKey;

	@Bean
	public AmazonDynamoDB amazonDynamoDB() {
		AmazonDynamoDB dynamoDB = new AmazonDynamoDBClient(amazonAWSCredentials());

		if (!StringUtils.isNullOrEmpty(dBEndpoint)) {
			dynamoDB.setEndpoint(dBEndpoint);
		}

		return dynamoDB;
	}

	@Bean
	public AWSCredentials amazonAWSCredentials() {
		return new BasicAWSCredentials(accessKey, secretKey);
	}
}

Define Spring JPA Entity Model

We create a Customer model class with 6 attributes:

  • id
  • firstname
  • lastname
  • address
  • age
  • copyright

– Coding:


package com.javasampleapproach.dynamodb.model;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;

@DynamoDBTable(tableName = "Customer")
public class Customer {

	private String id;
	private String firstName;
	private String lastName;
	private int age;
	private String address;
	private String copyright;

	public Customer() {
	}

	public Customer(String id, String firstName, String lastName, int age, String address, String copyright) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age,
		this.address = address,
		this.copyright = copyright
	}

	@DynamoDBHashKey(attributeName = "Id")
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@DynamoDBAttribute(attributeName = "FirstName")
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	@DynamoDBAttribute(attributeName = "LastName")
	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	@DynamoDBAttribute(attributeName = "copyright")
	public String getCopyright() {
		return copyright;
	}

	public void setCopyright(String copyright) {
		this.copyright = copyright;
	}	

	@DynamoDBAttribute(attributeName = "age")
	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.lastName = lastName;
	}
	
	@DynamoDBAttribute(attributeName = "address")
	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
	
	@Override
	public String toString() {
		return String.format("Customer[id=%s, firstName='%s', lastName='%s', age='%d', address='%s']", id, firstName, lastName, age, address);
	}
}

@DynamoDBAttribute:


@Retention(value=RUNTIME)
 @Target(value={FIELD,METHOD})
public @interface DynamoDBAttribute

– Interface for marking a class property as an attribute in a DynamoDB table. Applied to the getter method or the class field for a modeled property. If the annotation is applied directly to the class field, the corresponding getter and setter must be declared in the same class.
– This annotation is optional when the name of the DynamoDB attribute matches the name of the property declared in the class. When they differ, use this annotation with the attributeName() parameter to specify which DynamoDB attribute this property corresponds to. Furthermore, the DynamoDBMapper class assumes Java naming conventions, and will lower-case the first character of a getter method’s property name to determine the name of the property. E.g., a method getValue() will map to the DynamoDB attribute “value”. Similarly, a method isValid() maps to the DynamoDB attribute “valid”.

Define SpringBoot JPA Repository – SpringBoot React DynamoDB CRUD

For doing CRUD operations with database, we define an interface CustomerRepository that extends class JpaRepository:


package com.loizenai.dynamodb.repo;

import java.util.List;

import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.springframework.data.repository.CrudRepository;

import com.javasampleapproach.dynamodb.model.Customer;

@EnableScan
public interface CustomerRepository extends CrudRepository {

	List findByFirstName(String firstName);
}

Implement SpringBoot DynamoDB CRUD RestAPIs

Related post: SpringBoot RestAPIs @GetMapping, @PostMapping, @DeleteMapping, @PutMapping, @PatchMapping

We use SpringWeb to implement 4 RestAPIs for Post/Get/Put/Delete requests as below list:

  • SpringBoot Post request – we define a Post RestApi: /api/customer is used to save a single Customer data to DynamoDB database.
  • SpringBoot Get request – we define a GET RestApi: /api/customers is used to retrieve all Customer data from DynamoDB database.
  • SpringBoot Put request – we define a restapi /api/customer to update a Customer data from DynamoDB via the request body’s data
  • SpringBoot Delete request – we define a Delete RestApi: /api/customer/{id} is used to delete a Customer document from DynamoDB via a give id
package com.loizenai.springboot.reactjs.controller;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.loizenai.springboot.reactjs.model.Customer;
import com.loizenai.springboot.reactjs.repository.CustomerRepository;

@RestController
@RequestMapping("/api")
public class CustomerController {


    private final Logger log = LoggerFactory.getLogger(CustomerController.class);
    private CustomerRepository customerRepository;
    
    public CustomerController(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }
    
    @GetMapping("/customers")
    Collection<Customer> customers() {
        return customerRepository.findAll();
    }
    
    @GetMapping("/customer/{id}")
    ResponseEntity<?> getCustomer(@PathVariable Long id) {
        Optional<Customer> customer = customerRepository.findById(id);
        return customer.map(response -> ResponseEntity.ok().body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    
    @PostMapping("/customer")
    ResponseEntity<Customer> createCustomer(@RequestBody Customer customer) throws URISyntaxException {
        log.info("Request to create customer: {}", customer);
        Customer result = customerRepository.save(customer);
        return ResponseEntity.created(new URI("/api/group/" + result.getId()))
                .body(result);
    }
    
    @PutMapping("/customer")
    ResponseEntity<Customer> updateGroup(@RequestBody Customer customer) {
        log.info("Request to update customer: {}", customer);
        Customer result = customerRepository.save(customer);
        return ResponseEntity.ok().body(result);
    }
    
    @DeleteMapping("/customer/{id}")
    public ResponseEntity<?> deleteCustomer(@PathVariable Long id) {
        log.info("Request to delete customer: {}", id);
        customerRepository.deleteById(id);
        return ResponseEntity.ok().build();
    }
}

API Testing – SpringBoot DynamoDB CRUD RestAPIs testsuite

– Run DynamoDB:


java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

– Create Customer Table:


aws dynamodb create-table --table-name Customer --attribute-definitions AttributeName=Id,AttributeType=S --key-schema AttributeName=Id,KeyType=HASH --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 --endpoint-url http://localhost:8000

Response is like:


{
    "TableDescription": {
        "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/Customer",
        "AttributeDefinitions": [
            {
                "AttributeName": "Id",
                "AttributeType": "S"
            }
        ],
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 1,
            "LastIncreaseDateTime": 0.0,
            "ReadCapacityUnits": 1,
            "LastDecreaseDateTime": 0.0
        },
        "TableSizeBytes": 0,
        "TableName": "Customer",
        "TableStatus": "ACTIVE",
        "KeySchema": [
            {
                "KeyType": "HASH",
                "AttributeName": "Id"
            }
        ],
        "ItemCount": 0,
        "CreationDateTime": 1514538274.168
    }
}

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

Request 1
http://localhost:8080/save
The browser returns Done and if checking database with Customer table, we can see some data rows has been added:
SpringData DynamoDB CRUD Example - spring-data-postgresql-table-result-save

More at: SpringData DynamoDB CRUD Example | SpringBoot

Reactjs CRUD Application Example – Frontend Development

Reactjs CRUD Application Overview with SpringBoot RestAPIs

React.js project structure
React.js project structure
Reactjs CRUD RestAPI Application Frontend Architecture Diagram
Reactjs CRUD RestAPI Application Frontend Architecture Diagram

For more details, we go back to the session: Reactjs CRUD Application Overview with SpringBoot RestAPIs

How to build Reactjs Application?

In the tutorial “SpringBoot React DynamoDB CRUD”, we build a Reactjs Application that fetchs data from DynamoDB database through DynamoDB RestAPI with 5 UI components. Step to do:
– Setup Reactjs Application
– Build Reactjs Navigation Bar component
– Build Reactjs Home page component
– Build Reactjs CustomerList Component
– Build Reactjs CustomerEdit Component
– Update Reactjs App.js Component with Router

Setup Reactjs Application with Bootstrap

Create React App is a command line utility that generates React projects for you. It’s a convenient tool because it also offers commands that will build and optimize your project for production.
The create-react-app will set up everything you need to run a React application.

– Create a new project in the app directory with Yarn.

yarn create react-app app

Project Structure:

Start Setup React-project-structure
Start Setup React-project-structure

More details you can see at: Create Reactjs Project

After the app creation process completes, navigate into the app directory and install Bootstrap, cookie support for React, React Router, and Reactstrap.

Reactstrap: This library contains React Bootstrap 4 components that favor composition and control. The library does not depend on jQuery or Bootstrap javascript.
– React Router: Components are the heart of React’s powerful, declarative programming model. React Router is a collection of navigational components that compose declaratively with your application.

cd app
yarn add bootstrap@4.1.3 react-cookie@3.0.4 react-router-dom@4.3.1 reactstrap@6.5.0

Build Application Navigation Bar Component

import React, { Component } from 'react';
import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';

export default class AppNavbar extends Component {
  constructor(props) {
    super(props);
    this.state = {isOpen: false};
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  render() {
    return <Navbar color="dark" dark expand="md">
      <NavbarBrand tag={Link} to="/">Home</NavbarBrand>
      <NavbarToggler onClick={this.toggle}/>
      <Collapse isOpen={this.state.isOpen} navbar>
        <Nav className="ml-auto" navbar>
          <NavItem>
            <NavLink
              href="https://loizenai.com">loizenai.com</NavLink>
          </NavItem>
          <NavItem>
            <NavLink href="https://github.com/loizenai">GitHub</NavLink>
          </NavItem>
        </Nav>
      </Collapse>
    </Navbar>;
  }
}

Create Reactjs Home Page Component

 SpringBoot React DynamoDB CRUD - Project Goal - Home Page
Project Goal – Home Page
import React, { Component } from 'react';
import './App.css';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';
import { Button, Container } from 'reactstrap';

class Home extends Component {
  render() {
    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <Button color="link"><Link to="/customers">Manage Customer List</Link></Button>
        </Container>
      </div>
    );
  }
}

export default Home;

Build Reactjs CustomerList Component

Project Goal - Customer List
Project Goal – Customer List

– CustomerList Component will fetch a list of customers from SpringBoot RestAPI api/customers and then shows all of them on a Bootstrap table.
– The CustomerList has 3 buttons:

  • Add Customer & Edit are used to link to a url /customers/new that will map with CustomerEdit component
  • Delete button is used to remove a Customer entity from DynamoDB data based on a given id through an async function remove(id) that will do a fetch request with DELETE method to SpringBoot RestAPI.

Detail coding:

import React, { Component } from 'react';
import { Button, ButtonGroup, Container, Table } from 'reactstrap';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';

class CustomerList extends Component {

  constructor(props) {
    super(props);
    this.state = {customers: [], isLoading: true};
    this.remove = this.remove.bind(this);
  }

  componentDidMount() {
    this.setState({isLoading: true});

    fetch('api/customers')
      .then(response => response.json())
      .then(data => this.setState({customers: data, isLoading: false}));
  }

  async remove(id) {
    await fetch(`/api/customer/${id}`, {
      method: 'DELETE',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }).then(() => {
      let updatedCustomers = [...this.state.customers].filter(i => i.id !== id);
      this.setState({customers: updatedCustomers});
    });
  }

  render() {
    const {customers, isLoading} = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }

    const customerList = customers.map(customer => {
      return <tr key={customer.id}>
        <td style={{whiteSpace: 'nowrap'}}>{customer.firstname}</td>
        <td>{customer.lastname}</td>
        <td>{customer.age}</td>
        <td>{customer.address}</td>
        <td><a href={customer.copyright}>{customer.copyright}</a></td>
        <td>
          <ButtonGroup>
            <Button size="sm" color="primary" tag={Link} to={"/customers/" + customer.id}>Edit</Button>
            <Button size="sm" color="danger" onClick={() => this.remove(customer.id)}>Delete</Button>
          </ButtonGroup>
        </td>
      </tr>
    });

    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <div className="float-right">
            <Button color="success" tag={Link} to="/customers/new">Add Customer</Button>
          </div>
          <h3>Customer List</h3>
          <Table className="mt-4">
            <thead>
              <tr>
                <th width="20%">Firstname</th>
                <th width="20%">Lastname</th>
                <th width="10%">Age</th>
                <th>Address</th>
                <th>Copyrightby</th>
                <th width="10%">Actions</th>
              </tr>
            </thead>
            <tbody>
            {customerList}
            </tbody>
          </Table>
        </Container>
      </div>
    );
  }
}

export default CustomerList;

Build Reactjs CustomerEdit Component

SpringBoot React DynamoDB CRUD - Project Goal - Update Customer
Project Goal – Update Customer

We create a React Form to Put/Post data to DynamoDB database through SpringBoot RestAPI by using a fetch (PUT/POST) function:

  async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/customer', {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
    });
    this.props.history.push('/customers');
  }

After form submition, React Application will come back to a CustomerList component by using a coding-line:

this.props.history.push('/customers');

– Full coding:

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';
import AppNavbar from './AppNavbar';

class CustomerEdit extends Component {

  emptyCustomer = {
    firstname: '',
    lastname: '',
    age: '',
    address: '',
    copyrigtby: ''
  };

  constructor(props) {
    super(props);
    this.state = {
      item: this.emptyCustomer
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  async componentDidMount() {
    if (this.props.match.params.id !== 'new') {
      const customer = await (await fetch(`/api/customer/${this.props.match.params.id}`)).json();
      this.setState({item: customer});
    }
  }

  handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    let item = {...this.state.item};
    item[name] = value;
    this.setState({item});
  }

  async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/customer', {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
    });
    this.props.history.push('/customers');
  }

  render() {
    const {item} = this.state;
    const title = <h2>{item.id ? 'Edit Customer' : 'Add Customer'}</h2>;

    return <div>
      <AppNavbar/>
      <Container>
        {title}
        <Form onSubmit={this.handleSubmit}>
          <FormGroup>
            <Label for="firstname">Firstname</Label>
            <Input type="text" name="firstname" id="firstname" value={item.firstname || ''}
                   onChange={this.handleChange} autoComplete="firstname"/>
          </FormGroup>
          <FormGroup>
            <Label for="lastname">Lastname</Label>
            <Input type="text" name="lastname" id="lastname" value={item.lastname || ''}
                   onChange={this.handleChange} autoComplete="lastname"/>
          </FormGroup>          
          <FormGroup>
            <Label for="age">Age</Label>
            <Input type="text" name="age" id="age" value={item.age || ''}
                   onChange={this.handleChange} autoComplete="age"/>
          </FormGroup>
          <FormGroup>
            <Label for="address">Address</Label>
            <Input type="text" name="address" id="address" value={item.address || ''}
                   onChange={this.handleChange} autoComplete="address"/>
          </FormGroup>
          <FormGroup>
            <Button color="primary" type="submit">Save</Button>{' '}
            <Button color="secondary" tag={Link} to="/customers">Cancel</Button>
          </FormGroup>
        </Form>
      </Container>
    </div>
  }
}

export default withRouter(CustomerEdit);

Edit Reactjs App.js Component

App.js uses React Router to navigate between components.

  • path “/” is mapped with Home component
  • path “/customers” is mapped with CustomerList component
  • path “customers/:id” is mapped with CustomerEdit component
import React, { Component } from 'react';
import './App.css';
import Home from './Home';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import CustomerList from './CustomerList';
import CustomerEdit from './CustomerEdit';

class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route path='/' exact={true} component={Home}/>
          <Route path='/customers' exact={true} component={CustomerList}/>
          <Route path='/customers/:id' component={CustomerEdit}/>
        </Switch>
      </Router>
    )
  }
}

export default App;

Add a Proxy Setting for calling RestAPIs

To proxy from /api to http://localhost:8080/api, add a proxy setting to app/package.json.

"scripts": {...},
"proxy": "http://localhost:8080",

Integrative Testing: Reactjs Application with SpringBoot CRUD RestAPIs + DynamoDB

– Start Reactjs Application by cmd: yarn start.

Project Goal - Home Page
Project Goal – Home Page

Testcase 1: Reactjs Post request – Post data to DynamoDB through SpringBoot RestAPI

SpringBoot React DynamoDB CRUD - Reactjs Post data to DynamoDB through SpringBoot RestAPI - Add a Customer
Reactjs Post data to DynamoDB through SpringBoot RestAPI – Add a Customer

Testcase 2: Reactjs Put request – Put data to DynamoDB through SpringBoot RestAPI

Reactjs SpringBoot PUT request to DynamoDB - Update Customer
Reactjs SpringBoot PUT request to DynamoDB – Update Customer

Testcase 3: Reactjs Fetch request – Get All data from DynamoDB through SpringBoot RestAPI

Reactjs SpringBoot Get request - Get List Customers after update
Reactjs SpringBoot Get request – Get List Customer after update

Testcase 4: Reactjs Delete request – Delete an entity from DynamoDB through SpringBoot RestAPI

– Delete a Customer “Adam” with id=2:

List Customer after Delete successfully
List Customer after Delete successfully

Further Reading

Related posts – SpringBoot React DynamoDB CRUD:


Sourcecode

– Full Sourcecode: React.js + SpringBoot + DynamoDB

1. Reactjs

React.js-SpringBoot-postgresql-CRUD-Example

2. SpringBoot RestAPI

SpringBoot-Reactjs-postgresql-CRUD-Example

– Github Sourcecode:

1. Reactjs.

Reactjs – Github

2. SpringBoot RestAPI:

SpringBoot Reactjs CRUD DynamoDB RestAPI – Github

Read more about Java AWS DynamoDB database

Related Tutorials:

Angular SpringBoot CRUD DynamoDB
Reactjs SpringBoot CRUD PostgreSQL
Spring Data DynamoDB CRUD Example
SpringBoot Reactjs MongoDB CRUD

Leave a Reply

Your email address will not be published. Required fields are marked *