├── .gitignore
├── README.md
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── App.css
├── App.js
├── App.test.js
├── AppNavbar.js
├── CustomerEdit.js
├── CustomerList.js
├── Home.js
├── index.css
├── index.js
├── logo.svg
├── serviceWorker.js
└── setupTests.js
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SpringBoot + React + PostgreSQL: SpringBoot React.js CRUD Example
2 |
3 | 
4 |
5 | In the tutorial, I introduce how to build an “SpringBoot React.js CRUD PostgreSQL Example” project with the help of SpringData JPA for POST/GET/PUT/DELETE requests with step by step coding examples:
6 |
7 | – SpringBoot project produces CRUD RestAPIs with PostgreSQL database using the supporting of Spring Data JPA.
8 | – React.js project will consume the SpringBoot CRUD RestAPIs by Ajax then show up on Reactjs component’s views.
9 |
10 | List to do:
11 |
12 | – I draw a fullstack overview Diagram Architecture from React.js Frontend to PostgreSQL database through SpringBoot RestAPI backend.
13 | – Develop SpringBoot CRUD RestAPIs with the supporting of SpringWeb Framework.
14 | – Implement Reactjs CRUD application with Ajax fetching APIs to do CRUD request (Post/Get/Put/Delete) to SpringBoot Backend APIs.
15 | – 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 PostgreSQL database.
16 |
17 | ## Overall Architecture System: Reactjs + SpringBoot + PostgreSQL
18 |
19 | 
20 |
21 | - We build a backend: SpringBoot CRUD Application with PostgreSQL that provides RestAPIs for POST/GET/PUT/DELETE data entities and store them in PostgreSQL database.
22 | - 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.
23 |
24 | ## SpringBoot PostgreSQL CRUD Design Application
25 |
26 | 
27 |
28 | I build a SpringBoot project that handle all Post/Get/Put/Delete requests from RestClient and do CRUD operations to PostgreSQL database to save/retrieve/update and delete entity from PostgreSQL and returns back to Restclient the corresponding messages.
29 |
30 | We build a SpringBoot project with 2 layers:
31 | – SpringJPA Repository is used to interact with PostgreSQL database by a set of CRUD operations.
32 | – 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.
33 |
34 | ## Reactjs CRUD Application Design
35 |
36 | 
37 |
38 | – Reactjs CRUD Application is designed with 2 main layers:
39 |
40 | React.js components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
41 | Ajax is used by Reactjs component to fetch (post/put/get/delete) data from remote restapi by http request
42 |
43 | Reactjs CRUD Application defines 5 components:
44 |
45 | - Home.js is used serve as the landing page for your app.
46 | - AppNavbar.js is used to establish a common UI feature between components.
47 | - CustomerList.js is used to show all customers in the web-page
48 | - CustomerEdit.js is used to modify the existed customer
49 | - App.js uses React Router to navigate between components.
50 |
51 | ## Integrative Project Goal
52 |
53 | 
54 |
55 |
56 | Tutorial Link: [SpringBoot + React + PostgreSQL](https://loizenai.com/reactjs-springboot-crud-postgresql/)
57 |
58 | Reactjs + SpringBoot serial:
59 |
60 | Reactjs SpringBoot serial tutorials:
61 | - [How to Integrate Reactjs with SpringBoot Tutorial](https://loizenai.com/integrate-reactjs-springboot/)
62 | - [SpringBoot + React + MySQL: SpringBoot React.js CRUD Example](https://loizenai.com/springboot-react-mysql-crud-example/)
63 | - [SpringBoot + React + PostgreSQL: SpringBoot React.js CRUD Example](https://loizenai.com/reactjs-springboot-crud-postgresql/)
64 |
65 | Related posts:
66 |
67 | - [Angular 10 + Nodejs JWT Token Based Authentication with MongoDB Example – Express RestAPIs + JWT + BCryptjs + Sequelize](https://loizenai.com/angular-10-nodejs-jwt-authentication-MongoDB-examples-tutorials/)
68 | - [SpringBoot + Angular 9 + PostgreSQL CRUD Example – Architecture Diagram](https://loizenai.com/springboot-angular-9-postgresql-crud-example-architecture-diagram/)
69 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "app",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.3.2",
8 | "@testing-library/user-event": "^7.1.2",
9 | "bootstrap": "4.1.3",
10 | "react": "^16.14.0",
11 | "react-cookie": "3.0.4",
12 | "react-dom": "^16.14.0",
13 | "react-router-dom": "4.3.1",
14 | "react-scripts": "3.4.3",
15 | "reactstrap": "6.5.0"
16 | },
17 | "scripts": {
18 | "start": "react-scripts start",
19 | "build": "react-scripts build",
20 | "test": "react-scripts test",
21 | "eject": "react-scripts eject"
22 | },
23 | "proxy": "http://localhost:8080",
24 | "eslintConfig": {
25 | "extends": "react-app"
26 | },
27 | "browserslist": {
28 | "production": [
29 | ">0.2%",
30 | "not dead",
31 | "not op_mini all"
32 | ],
33 | "development": [
34 | "last 1 chrome version",
35 | "last 1 firefox version",
36 | "last 1 safari version"
37 | ]
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loizenai/reactjs-springboot-postgresql/521c4bb415ae8b6b74a4b0c36ff6187fa4618a31/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loizenai/reactjs-springboot-postgresql/521c4bb415ae8b6b74a4b0c36ff6187fa4618a31/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loizenai/reactjs-springboot-postgresql/521c4bb415ae8b6b74a4b0c36ff6187fa4618a31/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
40 | .container, .container-fluid {
41 | margin-top: 20px;
42 | }
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import './App.css';
3 | import Home from './Home';
4 | import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
5 | import CustomerList from './CustomerList';
6 | import CustomerEdit from './CustomerEdit';
7 |
8 | class App extends Component {
9 | render() {
10 | return (
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | )
19 | }
20 | }
21 |
22 | export default App;
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import App from './App';
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render();
7 | const linkElement = getByText(/learn react/i);
8 | expect(linkElement).toBeInTheDocument();
9 | });
10 |
--------------------------------------------------------------------------------
/src/AppNavbar.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';
3 | import { Link } from 'react-router-dom';
4 |
5 | export default class AppNavbar extends Component {
6 | constructor(props) {
7 | super(props);
8 | this.state = {isOpen: false};
9 | this.toggle = this.toggle.bind(this);
10 | }
11 |
12 | toggle() {
13 | this.setState({
14 | isOpen: !this.state.isOpen
15 | });
16 | }
17 |
18 | render() {
19 | return
20 | Home
21 |
22 |
23 |
32 |
33 | ;
34 | }
35 | }
--------------------------------------------------------------------------------
/src/CustomerEdit.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { Link, withRouter } from 'react-router-dom';
3 | import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';
4 | import AppNavbar from './AppNavbar';
5 |
6 | class CustomerEdit extends Component {
7 |
8 | emptyCustomer = {
9 | firstname: '',
10 | lastname: '',
11 | age: '',
12 | address: '',
13 | copyrigtby: ''
14 | };
15 |
16 | constructor(props) {
17 | super(props);
18 | this.state = {
19 | item: this.emptyCustomer
20 | };
21 | this.handleChange = this.handleChange.bind(this);
22 | this.handleSubmit = this.handleSubmit.bind(this);
23 | }
24 |
25 | async componentDidMount() {
26 | if (this.props.match.params.id !== 'new') {
27 | const customer = await (await fetch(`/api/customer/${this.props.match.params.id}`)).json();
28 | this.setState({item: customer});
29 | }
30 | }
31 |
32 | handleChange(event) {
33 | const target = event.target;
34 | const value = target.value;
35 | const name = target.name;
36 | let item = {...this.state.item};
37 | item[name] = value;
38 | this.setState({item});
39 | }
40 |
41 | async handleSubmit(event) {
42 | event.preventDefault();
43 | const {item} = this.state;
44 |
45 | await fetch('/api/customer', {
46 | method: (item.id) ? 'PUT' : 'POST',
47 | headers: {
48 | 'Accept': 'application/json',
49 | 'Content-Type': 'application/json'
50 | },
51 | body: JSON.stringify(item),
52 | });
53 | this.props.history.push('/customers');
54 | }
55 |
56 | render() {
57 | const {item} = this.state;
58 | const title = {item.id ? 'Edit Customer' : 'Add Customer'}
;
59 |
60 | return
61 |
62 |
63 | {title}
64 |
90 |
91 |
92 | }
93 | }
94 |
95 | export default withRouter(CustomerEdit);
--------------------------------------------------------------------------------
/src/CustomerList.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { Button, ButtonGroup, Container, Table } from 'reactstrap';
3 | import AppNavbar from './AppNavbar';
4 | import { Link } from 'react-router-dom';
5 |
6 | class CustomerList extends Component {
7 |
8 | constructor(props) {
9 | super(props);
10 | this.state = {customers: [], isLoading: true};
11 | this.remove = this.remove.bind(this);
12 | }
13 |
14 | componentDidMount() {
15 | this.setState({isLoading: true});
16 |
17 | fetch('api/customers')
18 | .then(response => response.json())
19 | .then(data => this.setState({customers: data, isLoading: false}));
20 | }
21 |
22 | async remove(id) {
23 | await fetch(`/api/customer/${id}`, {
24 | method: 'DELETE',
25 | headers: {
26 | 'Accept': 'application/json',
27 | 'Content-Type': 'application/json'
28 | }
29 | }).then(() => {
30 | let updatedCustomers = [...this.state.customers].filter(i => i.id !== id);
31 | this.setState({customers: updatedCustomers});
32 | });
33 | }
34 |
35 | render() {
36 | const {customers, isLoading} = this.state;
37 |
38 | if (isLoading) {
39 | return Loading...
;
40 | }
41 |
42 | const customerList = customers.map(customer => {
43 | return
44 | {customer.firstname} |
45 | {customer.lastname} |
46 | {customer.age} |
47 | {customer.address} |
48 | {customer.copyright} |
49 |
50 |
51 |
52 |
53 |
54 | |
55 |
56 | });
57 |
58 | return (
59 |
60 |
61 |
62 |
63 |
64 |
65 | Customer List
66 |
67 |
68 |
69 | Firstname |
70 | Lastname |
71 | Age |
72 | Address |
73 | Copyrightby |
74 | Actions |
75 |
76 |
77 |
78 | {customerList}
79 |
80 |
81 |
82 |
83 | );
84 | }
85 | }
86 |
87 | export default CustomerList;
--------------------------------------------------------------------------------
/src/Home.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import './App.css';
3 | import AppNavbar from './AppNavbar';
4 | import { Link } from 'react-router-dom';
5 | import { Button, Container } from 'reactstrap';
6 |
7 | class Home extends Component {
8 | render() {
9 | return (
10 |
11 |
12 |
13 |
14 |
15 |
16 | );
17 | }
18 | }
19 |
20 | export default Home;
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 | import 'bootstrap/dist/css/bootstrap.min.css';
7 |
8 | ReactDOM.render(
9 |
10 |
11 | ,
12 | document.getElementById('root')
13 | );
14 |
15 | // If you want your app to work offline and load faster, you can change
16 | // unregister() to register() below. Note this comes with some pitfalls.
17 | // Learn more about service workers: https://bit.ly/CRA-PWA
18 | serviceWorker.unregister();
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------