├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── LICENSE ├── README.md ├── mvnw ├── mvnw.cmd ├── package-lock.json ├── package.json ├── pom.xml ├── src ├── main │ ├── java │ │ └── com │ │ │ └── datsystemz │ │ │ └── nyakaz │ │ │ └── springbootreactjsfullstack │ │ │ ├── SpringBootReactJsFullstackApplication.java │ │ │ ├── controllers │ │ │ ├── UserController.java │ │ │ └── WebMainController.java │ │ │ ├── exceptions │ │ │ └── ResourceNotFoundException.java │ │ │ ├── models │ │ │ └── User.java │ │ │ └── repositories │ │ │ └── UserRepository.java │ ├── js │ │ └── App.js │ └── resources │ │ ├── application.properties │ │ ├── static │ │ └── main.css │ │ └── templates │ │ └── index.html └── test │ └── java │ └── com │ └── datsystemz │ └── nyakaz │ └── springbootreactjsfullstack │ ├── SpringBootReactJsFullstackApplicationTests.java │ └── UserTests.java └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | 35 | 36 | ### REACT JS ### 37 | # Logs 38 | logs 39 | *.log 40 | npm-debug.log* 41 | yarn-debug.log* 42 | yarn-error.log* 43 | 44 | # Runtime data 45 | pids 46 | *.pid 47 | *.seed 48 | *.pid.lock 49 | 50 | # Directory for instrumented libs generated by jscoverage/JSCover 51 | lib-cov 52 | 53 | # Coverage directory used by tools like istanbul 54 | coverage 55 | 56 | # nyc test coverage 57 | .nyc_output 58 | 59 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 60 | .grunt 61 | 62 | # Bower dependency directory (https://bower.io/) 63 | bower_components 64 | 65 | # node-waf configuration 66 | .lock-wscript 67 | 68 | # Compiled binary addons (http://nodejs.org/api/addons.html) 69 | build/Release 70 | 71 | # Dependency directories 72 | node_modules/ 73 | jspm_packages/ 74 | 75 | # Distribution directories 76 | dist/ 77 | 78 | # Typescript v1 declaration files 79 | typings/ 80 | 81 | # Optional npm cache directory 82 | .npm 83 | 84 | # Optional eslint cache 85 | .eslintcache 86 | 87 | # Optional REPL history 88 | .node_repl_history 89 | 90 | # Output of 'npm pack' 91 | *.tgz 92 | 93 | # Yarn Integrity file 94 | .yarn-integrity 95 | 96 | # dotenv environment variables file 97 | .env -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyakaz73/spring-boot-reactjs-fullstack/cf532f8e4362fc2bb4d103a35d7b6f9cc606134f/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Tafadzwa Lameck Nyamukapa 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring boot and React js fullstack application Part(1/2). 2 | Full stack application with Spring boot and React js, with **WEBPACK & BABEL. JUNIT Tests , RESTful API.** 3 | 4 | ### Show some :heart: and :star: the repo to support the project 5 | 6 | I like explaining things in code so without wasting much of your time lets just jump straight in and i will be explaining as we go. 7 | 8 | ## 1. Spring Boot (Initializer) 9 | To start off with you can use Spring Initializr to get the Spring Boot project structure for you, and this can be found [here](https://start.spring.io/) 10 | 11 | Once you get there in this case im using Maven , and that's my personal preference over Gradle since it gives a nice xml layout for your setup , in terms of installing dependency , plugins etc. its essentially a tool for your project management, just like package.json for those who are familiar with node js. 12 | 13 | You also need to add a couple of dependencies which are 14 | * JPA - Data persistence in SQL stores with Java Persistence API 15 | * thymeleaf - A modern server-side Java template engine 16 | * WEB - Build web, including RESTful, applications using Spring MVC 17 | * H2 - Provides a volatile in-memory database 18 | * Lombok - Java annotation library which helps reduce boilerplate code 19 | 20 | ## 2. Rest API Service 21 | Now lets create the REST API service for the backend application which will be able to perform basic **CRUD** (Create, Read, Update ,Delete) functionality. 22 | 23 | ### a. models 24 | First create a package name models. 25 | Inside models create class User for your user model. See code below 26 | 27 | ```java 28 | 29 | package com.datsystemz.nyakaz.springbootreactjsfullstack.models; 30 | 31 | import javax.persistence.Entity; 32 | import javax.persistence.GeneratedValue; 33 | import javax.persistence.GenerationType; 34 | import javax.persistence.Id; 35 | 36 | @Entity 37 | public class User { 38 | 39 | @Id 40 | @GeneratedValue(strategy = GenerationType.AUTO) 41 | private Long id; 42 | private String name; 43 | private String surname; 44 | private String email; 45 | private String username; 46 | private String password; 47 | 48 | protected User(){} 49 | 50 | public User(String name, String surname, String email, String username, String password){ 51 | this.name = name; 52 | this.surname = surname; 53 | this.email = email; 54 | this.username = username; 55 | this.password = password; 56 | } 57 | 58 | public Long getId(){ 59 | return id; 60 | } 61 | 62 | public String getName() { 63 | return name; 64 | } 65 | 66 | public String getSurname() { 67 | return surname; 68 | } 69 | 70 | public String getUsername() { 71 | return username; 72 | } 73 | 74 | public String getPassword() { 75 | return password; 76 | } 77 | 78 | public String getEmail() { 79 | return email; 80 | } 81 | 82 | public void setId(Long id) { 83 | this.id = id; 84 | } 85 | 86 | public void setName(String name) { 87 | this.name = name; 88 | } 89 | 90 | public void setSurname(String surname) { 91 | this.surname = surname; 92 | } 93 | 94 | public void setEmail(String email) { 95 | this.email = email; 96 | } 97 | 98 | public void setUsername(String username) { 99 | this.username = username; 100 | } 101 | 102 | public void setPassword(String password) { 103 | this.password = password; 104 | } 105 | } 106 | 107 | 108 | ``` 109 | 110 | First you will notice the @Entity annotation- this tell Spring that it is a JPA entity and it is mapped to table named User. If you want to the the table name you will have to annotate it with @Table(name = "new_table_name_here") 111 | You probably noticed that this is too much of code to create an entity not to worry, Remember the Lambok dependancy this is the best time to use it since it offers a functionality of writing code with less boiler plate of code. 112 | 113 | ```java 114 | package com.datsystemz.nyakaz.springbootreactjsfullstack.models; 115 | 116 | import lombok.AllArgsConstructor; 117 | import lombok.Data; 118 | import lombok.NoArgsConstructor; 119 | 120 | import javax.persistence.Entity; 121 | import javax.persistence.GeneratedValue; 122 | import javax.persistence.GenerationType; 123 | import javax.persistence.Id; 124 | 125 | @Entity 126 | @Data 127 | @NoArgsConstructor 128 | @AllArgsConstructor 129 | public class User { 130 | 131 | @Id 132 | @GeneratedValue(strategy = GenerationType.AUTO) 133 | private Long id; 134 | private String name; 135 | private String surname; 136 | private String email; 137 | private String username; 138 | private String password; 139 | 140 | 141 | } 142 | ``` 143 | In the above snippet you will notice we have added a couple of annotations 144 | @Data - is a convenient shortcut that bundles features of @toString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor . 145 | @NoArgsConstructor provides the default construct 146 | @AllArgsConstructor bundles the non default constructor. 147 | 148 | ### b. repositories 149 | Lets create a repositories package will an interface called UserRepository. The interface extends the Jpa repository so that we can have all methods that is provided by the JpaRepository that allows us to query our database. 150 | ```java 151 | package com.datsystemz.nyakaz.springbootreactjsfullstack.repositories; 152 | 153 | import com.datsystemz.nyakaz.springbootreactjsfullstack.models.User; 154 | import org.springframework.data.jpa.repository.JpaRepository; 155 | 156 | public interface UserRepository extends JpaRepository { 157 | } 158 | 159 | ``` 160 | ### c. controllers 161 | 162 | Now that you got you repository setup its time to create a controllers package and with a class called UserController. 163 | The is where the REST service with Spring begins. The controller will save all end points of our user controller, which will then be consumed by the outside world. 164 | All the action feature required by our CRUD app are going to seat here ie GET, POST, PUT and DELETE actions. See code below 165 | 166 | ```java 167 | package com.datsystemz.nyakaz.springbootreactjsfullstack.controllers; 168 | 169 | import com.datsystemz.nyakaz.springbootreactjsfullstack.exceptions.ResourceNotFoundException; 170 | import com.datsystemz.nyakaz.springbootreactjsfullstack.models.User; 171 | import com.datsystemz.nyakaz.springbootreactjsfullstack.repositories.UserRepository; 172 | import org.springframework.beans.factory.annotation.Autowired; 173 | import org.springframework.http.ResponseEntity; 174 | import org.springframework.web.bind.annotation.*; 175 | 176 | import java.util.List; 177 | 178 | @RestController 179 | public class UserController { 180 | private UserRepository userRepository; 181 | 182 | @Autowired 183 | public UserController(UserRepository userRepository){ 184 | this.userRepository = userRepository; 185 | } 186 | 187 | @PostMapping("/user/save") 188 | public User saveUser(@RequestBody User user){ 189 | return this.userRepository.save(user); 190 | } 191 | 192 | @GetMapping("/user/all") 193 | public ResponseEntity> getUsers(){ 194 | return ResponseEntity.ok( 195 | this.userRepository.findAll() 196 | ); 197 | } 198 | 199 | @GetMapping("/user/{id}") 200 | public ResponseEntity getUser(@PathVariable(value = "id" ) Long id){ 201 | User user = this.userRepository.findById(id).orElseThrow( 202 | ()-> new ResourceNotFoundException("User not found") 203 | ); 204 | 205 | return ResponseEntity.ok().body(user); 206 | } 207 | 208 | @PutMapping("user/{id}") 209 | public User updateUser(@RequestBody User newUser, @PathVariable(value = "id") Long id){ 210 | return this.userRepository.findById(id) 211 | .map(user -> { 212 | user.setName(newUser.getName()); 213 | user.setSurname(newUser.getSurname()); 214 | user.setEmail(newUser.getEmail()); 215 | user.setUsername(newUser.getUsername()); 216 | user.setPassword(newUser.getPassword()); 217 | return this.userRepository.save(user); 218 | }) 219 | .orElseGet(()->{ 220 | newUser.setId(id); 221 | return this.userRepository.save(newUser); 222 | }); 223 | } 224 | 225 | @DeleteMapping("user/{id}") 226 | public ResponseEntity removeUser(@PathVariable(value = "id") Long id){ 227 | User user =this.userRepository.findById(id).orElseThrow( 228 | ()-> new ResourceNotFoundException("User not found"+id) 229 | ); 230 | 231 | this.userRepository.delete(user); 232 | return ResponseEntity.ok().build(); 233 | } 234 | 235 | 236 | 237 | 238 | } 239 | 240 | ``` 241 | In the above code the class is annotated with @RestController telling Spring that the data returned by each method will be written straight into the response body instead of rendering a template. 242 | The UserRepository is injected by constructor into the controller. The @Autowired enable automatic dependency injection. 243 | 244 | The @PostMapping , @GetMapping, @PutMapping and @DeleteMapping corresponds to the POST, GET, UPDATE and DELETE actions. 245 | One thing to note here is the @DeleteMapping and @GetMapping which is calling a ResourceNotFoundException class that will output the runtime exception. 246 | 247 | Lets quickly implement the ResourceNotFoundException class. 248 | 249 | ### d. exceptions 250 | I like to keep my code clean and packaged. So just quickly create a package called exceptions with a class ResourceNotFoundException. See code below: 251 | 252 | ```java 253 | package com.datsystemz.nyakaz.springbootreactjsfullstack.exceptions; 254 | 255 | import org.springframework.http.HttpStatus; 256 | import org.springframework.web.bind.annotation.ResponseStatus; 257 | 258 | @ResponseStatus(value = HttpStatus.NOT_FOUND) 259 | public class ResourceNotFoundException extends RuntimeException{ 260 | public ResourceNotFoundException(String message){ 261 | super(message); 262 | } 263 | } 264 | 265 | ``` 266 | The above class extends the RuntimeException which will give us access to all methods that are in that class. In this case just call super in the constructor with message variable. 267 | That's it .,now whenever a user is not found it will return the run time exception with user not Found message and status of HttpStatus.NOT_FOUND. 268 | ### e. database 269 | 270 | * **NB** Since we have added the H2 in -memory DB . Spring automatically runs it whenever there is persistence to the db. Please note that H2 Database is volatile meaning it will be automatically be created when the server ran and whenever you stop the server it will tear down the db and its contents. 271 | By default, Spring Boot configures the application to connect to an in-memory store with the username sa and an empty password. However, we can change those parameters by adding the following properties to the application.properties file: 272 | 273 | ```properties 274 | spring.datasource.url=jdbc:h2:mem:testdb 275 | spring.datasource.driverClassName=org.h2.Driver 276 | spring.datasource.username=sa 277 | spring.datasource.password= 278 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 279 | # Enabling H2 Console 280 | spring.h2.console.enabled=true 281 | 282 | # Custom H2 Console URL 283 | spring.h2.console.path=/h2 284 | # Whether to enable remote access. 285 | spring.h2.console.settings.web-allow-others=true 286 | 287 | server.error.include-stacktrace=never 288 | ``` 289 | ### f. REST API TESTING(JPA UNIT TESTING) 290 | Now that everything is setup its time for the truth to be reviewed. I like to do things differently so instead of testing our API using Postman im going to do JPA Unit testing. 291 | If you are familiar with JPA Unit Testing feel free to test with Postman or jump to next section **(INTEGRATING REACTJS)** 292 | 293 | Now to get things started quickly install JPA Unit testing dependency in your pom.xml file. 294 | 295 | ```xml 296 | 297 | 298 | junit 299 | junit 300 | test 301 | 302 | ``` 303 | In your **test/java/com./** create a file class UserTests with the following testing code: 304 | 305 | ```java 306 | package com.datsystemz.nyakaz.springbootreactjsfullstack; 307 | 308 | import com.datsystemz.nyakaz.springbootreactjsfullstack.models.User; 309 | import com.datsystemz.nyakaz.springbootreactjsfullstack.repositories.UserRepository; 310 | import org.junit.Assert; 311 | import org.junit.jupiter.api.Test; 312 | import org.springframework.beans.factory.annotation.Autowired; 313 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 314 | 315 | 316 | @DataJpaTest 317 | public class UserTests { 318 | 319 | @Autowired 320 | private UserRepository userRepository; 321 | 322 | @Test 323 | public void testSaveUser(){ 324 | User user = new User("John","Doe","john.doe@email.com","johhny","strong-password"); 325 | userRepository.save(user); 326 | userRepository.findById(new Long(1)) 327 | .map(newUser ->{ 328 | Assert.assertEquals("John",newUser.getName()); 329 | return true; 330 | }); 331 | } 332 | 333 | @Test 334 | public void getUser(){ 335 | User user = new User("John","Doe","john.doe@email.com","johhny","strong-password"); 336 | User user2 = new User("Daniel","Marcus","daniel@daniel.com","danie","super_strong_password"); 337 | userRepository.save(user); 338 | 339 | userRepository.save(user2); 340 | 341 | userRepository.findById(new Long(1)) 342 | .map(newUser ->{ 343 | Assert.assertEquals("danie",newUser.getUsername()); 344 | return true; 345 | }); 346 | 347 | } 348 | 349 | @Test 350 | public void getUsers(){ 351 | User user = new User("John","Doe","john.doe@email.com","johhny","strong-password"); 352 | User user2 = new User("Daniel","Marcus","daniel@daniel.com","danie","super_strong_password"); 353 | userRepository.save(user); 354 | userRepository.save(user2); 355 | 356 | Assert.assertNotNull(userRepository.findAll()); 357 | } 358 | 359 | @Test 360 | public void deleteUser(){ 361 | User user = new User("John","Doe","john.doe@email.com","johhny","strong-password"); 362 | userRepository.save(user); 363 | userRepository.delete(user); 364 | Assert.assertTrue(userRepository.findAll().isEmpty()); 365 | } 366 | 367 | 368 | } 369 | ``` 370 | The @DataJpaTest tells Spring to test the persistence layer components that will autoconfigure in-memory embedded H2 database and scan for @Entity classes and Spring Data JPA repositories. 371 | We need to autowire the UserRepository so that we will have functions provided by the JPA to be able to query our DB. 372 | Spring will look for function annotated with @Test. The JUNIT ASSERT i going to assert most of the tests. 373 | 374 | In your terminal You can now run : 375 | 376 | ```cmd 377 | mvn test 378 | ``` 379 | If everything runs well you should have an output similar to this 380 | 381 | ``` 382 | [INFO] 383 | [INFO] Results: 384 | [INFO] 385 | [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 386 | [INFO] 387 | [INFO] ------------------------------------------------------------------------ 388 | [INFO] BUILD SUCCESS 389 | [INFO] ------------------------------------------------------------------------ 390 | [INFO] Total time: 11.845 s 391 | [INFO] Finished at: 2020-09-08T19:01:25+02:00 392 | [INFO] Final Memory: 32M/370M 393 | [INFO] ------------------------------------------------------------------------ 394 | ``` 395 | * **NB** At this point of your test runs successfully congratulations you have made it :) . Now you can jump in to the next section ie **(INTEGRATING REACTJS)** 396 | 397 | ## 3. INTEGRATING REACTJS 398 | 399 | Now lets jump in to the frontend of things of our fullstack application. 400 | 401 | In this section i am assuming you have already installed **nodejs** in your working environment. If not just quickly install link can be found [here](https://nodejs.org/en/) 402 | 403 | We are not going to use npm create-react-app to create our frontend since we dont want to separately run the react js application with its own proxy port usually port 3000. 404 | We want our Spring backend application to be able to **serve** the front at its default port 8080, that way we get to experience the **fullstack** of things without having to separately running two instances servers for our front end and backend application. 405 | 406 | Now you can prepare the react js project structure by creating these folders in your **root folder** of your application. 407 | 408 | ```cmd 409 | $ mkdir -p ./frontend/src/{components,actions,reducers} 410 | ``` 411 | The above command will create a folder structure that look like this: 412 | ```cmd 413 | frontend/ 414 | src/ 415 | actions/ 416 | components/ 417 | reducers/ 418 | 419 | ``` 420 | This is were your react frontend application is going to seat in. 421 | 422 | ### 3a Installing packages 423 | 424 | We now need to create a package.json file which will have all your dependencies that is going to be used by reactjs framework. 425 | To create the package.json file just run 426 | ```cmd 427 | $ npm init -y 428 | ``` 429 | Since you have already installed node this npm command should run just fine, and you now should be able to see the package.json file in your root folder of your project. 430 | 431 | Now at this point you now need to install the following Dev Dependencies and Dependencies for your react . 432 | 433 | ```cmd 434 | $ npm i -D webpack webpack-cli 435 | $ npm i -D babel-loader @babel/core @babel/preset-env @babel/preset-react @babel/plugin-proposal-class-properties 436 | $ npm i -D sass-loader css-loader 437 | $ npm i react react-dom react-router-dom 438 | $ npm i redux react-redux redux-thunk redux-devtools-extension 439 | $ npm i redux-form 440 | $ npm i axios 441 | $ npm i lodash 442 | ``` 443 | This will install the Dev Dependencies required by react js . 444 | * webpack - will bundle Javascript files for usage in a browser 445 | * babel - is a transpiler ie a Javascript compiler used to convert ECMAScript 2015+ code into a backwards compatible version of Javascript in current and older browser environments. 446 | * react - Javascript library for building user interfaces. Developed by facebook 447 | * redux - The is a predictable state container for Js apps 448 | * axios - Promise based HTTP client 449 | * lodash(optional) - Lodash is a reference library made with JavaScript. 450 | 451 | ### 3b Babel Configuration 452 | Add a file name .babelrc to the root directory and configure babel: 453 | 454 | ``` 455 | { 456 | "presets": [ 457 | [ 458 | "@babel/preset-env", 459 | { 460 | "targets": { 461 | "node": "current" 462 | }, 463 | "useBuiltIns": "usage", 464 | "corejs": 3 465 | } 466 | ], 467 | "@babel/preset-react" 468 | ], 469 | "plugins": ["@babel/plugin-proposal-class-properties"] 470 | } 471 | ``` 472 | 473 | 474 | ### 3c. Webpack Configuration 475 | 476 | Add a file named webpack.config.js to the root directory and configure webpack: 477 | 478 | ```js 479 | var path = require('path'); 480 | 481 | module.exports = { 482 | entry: './src/main/js/App.js', 483 | devtool: 'sourcemaps', 484 | cache: true, 485 | mode: 'development', 486 | output: { 487 | path: __dirname, 488 | filename: './src/main/resources/static/built/bundle.js' 489 | }, 490 | module: { 491 | rules: [ 492 | { 493 | test: path.join(__dirname, '.'), 494 | exclude: /(node_modules)/, 495 | use: [{ 496 | loader: 'babel-loader', 497 | options: { 498 | presets: ["@babel/preset-env", "@babel/preset-react"] 499 | } 500 | }] 501 | }, 502 | { 503 | test: /\.css$/, 504 | use: [ 505 | 'style-loader', 506 | 'css-loader' 507 | ] 508 | }, 509 | { 510 | test: /\.(png|svg|jpg|gif|eot|otf|ttf|woff|woff2)$/, 511 | use: [ 512 | { 513 | loader: 'url-loader', 514 | options: {} 515 | } 516 | ] 517 | } 518 | ] 519 | } 520 | }; 521 | ``` 522 | """Quote Spring Docs""" 523 | This webpack configuration file: 524 | 525 | * Defines the entry point as ./src/main/js/App.js. In essence, App.js (a module you will write shortly) is the proverbial public static void main() of our JavaScript application. webpack must know this in order to know what to launch when the final bundle is loaded by the browser. 526 | 527 | * Creates sourcemaps so that, when you are debugging JS code in the browser, you can link back to original source code. 528 | 529 | * Compile ALL of the JavaScript bits into ./src/main/resources/static/built/bundle.js, which is a JavaScript equivalent to a Spring Boot uber JAR. All your custom code AND the modules pulled in by the require() calls are stuffed into this file. 530 | 531 | * It hooks into the babel engine, using both es2015 and react presets, in order to compile ES6 React code into a format able to be run in any standard browser. 532 | 533 | With this webpack configuration file setup we now need to create a couple of directories 534 | 535 | ### 3d. React boiler plate Setup 536 | 1. Notice how the above webpack is referencing to ./src/main/js/App.js . Let create a js folder in main and an App.js file inside 537 | The App.js file should have this following code: 538 | ```typescript jsx 539 | import React, { Component } from "react"; 540 | import ReactDOM from "react-dom"; 541 | 542 | 543 | export class App extends Component { 544 | render() { 545 | return ( 546 |
547 |

Welcome to React Front End Served by Spring Boot

548 |
549 | ); 550 | } 551 | } 552 | 553 | export default App; 554 | 555 | ReactDOM.render(, document.querySelector("#app")); 556 | 557 | ``` 558 | 2. Now we now need to prepare the html that will render the App.js we just created in Spring 559 | 560 | Remember the Thymeleaf dependency we installed at the beginning in the Spring Initializer it time to get that to use 561 | To get started you need to create an index page in **src/main/resources/templates/index.html** 562 | 563 | ```html 564 | 565 | 566 | 567 | 568 | ReactJS + Spring Data REST 569 | 570 | 571 | 572 | 573 |
574 | 575 | 576 | 577 | 578 | 579 | ``` 580 | The key part in this template is the
component in the middle. It is where you will direct React to plug in the rendered output. 581 | 582 | The bundle.js will automatically generated when we run our application. 583 | 584 | Spring will automatically know that the main.css file will be created under the static folder in your resources folder so go ahead and create it will use it later. 585 | 586 | With that set up you should have the Final project structure now looking to something like this: 587 | 588 | ```cmd 589 | - frontend 590 | - sample-project-root 591 | - src 592 | - main 593 | -java 594 | - js 595 | App.js 596 | index.js 597 | - static 598 | main.css 599 | - resources 600 | - templates 601 | index.html 602 | webpack.config.js 603 | package.json 604 | pom.xml 605 | ``` 606 | If this is you project string you are good to go and now left with one last step to test this out. 607 | 608 | ### 3e. Script Setup in package.json 609 | In the package.json file we need to finally replace the script tag with the following 610 | 611 | ```json 612 | ... 613 | ... 614 | "scripts": { 615 | "watch": "webpack --watch -d --output ./target/classes/static/built/bundle.js" 616 | }, 617 | 618 | ... 619 | ... 620 | ``` 621 | This will run the webpack and tell it to render the output (bundle.js) to ./taget/classes/static/built/ folder. 622 | The --watch tag will tell the webpack to constantly watch for changes in our code so that when there is such it will update the bundle.js file. 623 | 624 | ### 3f. Final Setup Step 625 | Remember when we create our UserController it had a @RestController annotation to serve the rest methods in that class. 626 | If can still recall we said the @RestController tells Spring that the data returned by each method will be written straight into the response body instead of rendering a template. 627 | Now we need an endpoint that will render a template. S 628 | So lets create a separate class in our controllers called WebMainController which will render the index page of our react App.js main component. 629 | 630 | ```java 631 | package com.datsystemz.com.microfinancedatsystemz.controllers; 632 | 633 | import org.springframework.stereotype.Controller; 634 | import org.springframework.web.bind.annotation.RequestMapping; 635 | 636 | @Controller 637 | public class WebMainController { 638 | 639 | @RequestMapping(value = "/") 640 | public String index() { 641 | return "index"; 642 | } 643 | } 644 | 645 | ``` 646 | 647 | ## 4. FINAL TEST 648 | Now lets test the full stack application 649 | First run your server 650 | ```cmd 651 | $ mvn spring-boot:run 652 | ``` 653 | If there are no error you are good it means we haven't messed anything up since our last JUNIT TESTS. 654 | Finally transpile your react app by running: 655 | ```cmd 656 | $ npm run-script watch 657 | ``` 658 | Now you can go to you browser http://localhost:8080/ and if this appears on your browser: 659 | 660 | # Welcome to React Front End Served by Spring Boot 661 | 662 | Then you have successfully integrated react js and spring boot. Full stack application. If you make changes in your app webpack should be able to update those changes, and all you have to do is to restart your browser. 663 | 664 | I know this was a long tutorial I will make it in parts and will create a Part 2 of this as soon as i can . So that you will now Learn React. 665 | 666 | Thank you for taking your time in reading this article. 667 | 668 | !!END 669 | 670 | ### Source Code 671 | The source code can be found on my git repository [here](https://github.com/nyakaz73/spring-boot-reactjs-fullstack) 672 | 673 | ### Pull Requests 674 | I Welcome and i encourage all Pull Requests 675 | 676 | ## Created and Maintained by 677 | * Author: [Tafadzwa Lameck Nyamukapa](https://github.com/nyakaz73) : 678 | * Email: [tafadzwalnyamukapa@gmail.com] 679 | * Open for any collaborations and Remote Work!! 680 | * Happy Coding!! 681 | 682 | ### License 683 | 684 | ``` 685 | MIT License 686 | 687 | Copyright (c) 2020 Tafadzwa Lameck Nyamukapa 688 | 689 | Permission is hereby granted, free of charge, to any person obtaining a copy 690 | of this software and associated documentation files (the "Software"), to deal 691 | in the Software without restriction, including without limitation the rights 692 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 693 | copies of the Software, and to permit persons to whom the Software is 694 | furnished to do so, subject to the following conditions: 695 | 696 | The above copyright notice and this permission notice shall be included in all 697 | copies or substantial portions of the Software. 698 | 699 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 700 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 701 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 702 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 703 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 704 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 705 | SOFTWARE. 706 | 707 | 708 | ``` 709 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "spring-boot-react-js-fullstack", 3 | "version": "1.0.0", 4 | "description": "How to create a full stack application with Spring boot and React js, with web-pack and babel", 5 | "main": "index.js", 6 | "scripts": { 7 | "watch": "webpack --watch -d --output ./target/classes/static/built/bundle.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/nyakaz73/spring-boot-reactjs-fullstack.git" 12 | }, 13 | "keywords": [], 14 | "author": "", 15 | "license": "ISC", 16 | "bugs": { 17 | "url": "https://github.com/nyakaz73/spring-boot-reactjs-fullstack/issues" 18 | }, 19 | "homepage": "https://github.com/nyakaz73/spring-boot-reactjs-fullstack#readme", 20 | "devDependencies": { 21 | "@babel/core": "^7.11.6", 22 | "@babel/plugin-proposal-class-properties": "^7.10.4", 23 | "@babel/preset-env": "^7.11.5", 24 | "@babel/preset-react": "^7.10.4", 25 | "babel-loader": "^8.1.0", 26 | "css-loader": "^4.3.0", 27 | "sass-loader": "^10.0.2", 28 | "webpack": "^4.44.1", 29 | "webpack-cli": "^3.3.12" 30 | }, 31 | "dependencies": { 32 | "axios": "^0.20.0", 33 | "lodash": "^4.17.20", 34 | "react": "^16.13.1", 35 | "react-dom": "^16.13.1", 36 | "react-redux": "^7.2.1", 37 | "react-router-dom": "^5.2.0", 38 | "redux": "^4.0.5", 39 | "redux-devtools-extension": "^2.13.8", 40 | "redux-form": "^8.3.6", 41 | "redux-thunk": "^2.3.0" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.3.3.RELEASE 9 | 10 | 11 | com.datsystemz.nyakaz 12 | spring-boot-react-js-fullstack 13 | 0.0.1-SNAPSHOT 14 | spring-boot-react-js-fullstack 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-data-jpa 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-thymeleaf 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | 36 | com.h2database 37 | h2 38 | runtime 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | true 44 | 45 | 46 | junit 47 | junit 48 | test 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-test 53 | test 54 | 55 | 56 | org.junit.vintage 57 | junit-vintage-engine 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-maven-plugin 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /src/main/java/com/datsystemz/nyakaz/springbootreactjsfullstack/SpringBootReactJsFullstackApplication.java: -------------------------------------------------------------------------------- 1 | package com.datsystemz.nyakaz.springbootreactjsfullstack; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootReactJsFullstackApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootReactJsFullstackApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/datsystemz/nyakaz/springbootreactjsfullstack/controllers/UserController.java: -------------------------------------------------------------------------------- 1 | package com.datsystemz.nyakaz.springbootreactjsfullstack.controllers; 2 | 3 | import com.datsystemz.nyakaz.springbootreactjsfullstack.exceptions.ResourceNotFoundException; 4 | import com.datsystemz.nyakaz.springbootreactjsfullstack.models.User; 5 | import com.datsystemz.nyakaz.springbootreactjsfullstack.repositories.UserRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.util.List; 11 | 12 | @RestController 13 | public class UserController { 14 | private UserRepository userRepository; 15 | 16 | @Autowired 17 | public UserController(UserRepository userRepository){ 18 | this.userRepository = userRepository; 19 | } 20 | 21 | @PostMapping("/user/save") 22 | public User saveUser(@RequestBody User user){ 23 | return this.userRepository.save(user); 24 | } 25 | 26 | @GetMapping("/user/all") 27 | public ResponseEntity> getUsers(){ 28 | return ResponseEntity.ok( 29 | this.userRepository.findAll() 30 | ); 31 | } 32 | 33 | @GetMapping("/user/{id}") 34 | public ResponseEntity getUser(@PathVariable(value = "id" ) Long id){ 35 | User user = this.userRepository.findById(id).orElseThrow( 36 | ()-> new ResourceNotFoundException("User not found") 37 | ); 38 | 39 | return ResponseEntity.ok().body(user); 40 | } 41 | 42 | @PutMapping("user/{id}") 43 | public User updateUser(@RequestBody User newUser, @PathVariable(value = "id") Long id){ 44 | return this.userRepository.findById(id) 45 | .map(user -> { 46 | user.setName(newUser.getName()); 47 | user.setSurname(newUser.getSurname()); 48 | user.setEmail(newUser.getEmail()); 49 | user.setUsername(newUser.getUsername()); 50 | user.setPassword(newUser.getPassword()); 51 | return this.userRepository.save(user); 52 | }) 53 | .orElseGet(()->{ 54 | newUser.setId(id); 55 | return this.userRepository.save(newUser); 56 | }); 57 | } 58 | 59 | @DeleteMapping("user/{id}") 60 | public ResponseEntity removeUser(@PathVariable(value = "id") Long id){ 61 | User user =this.userRepository.findById(id).orElseThrow( 62 | ()-> new ResourceNotFoundException("User not found"+id) 63 | ); 64 | 65 | this.userRepository.delete(user); 66 | return ResponseEntity.ok().build(); 67 | } 68 | 69 | 70 | 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/datsystemz/nyakaz/springbootreactjsfullstack/controllers/WebMainController.java: -------------------------------------------------------------------------------- 1 | package com.datsystemz.nyakaz.springbootreactjsfullstack.controllers; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | 6 | @Controller 7 | public class WebMainController { 8 | 9 | @RequestMapping(value = "/") 10 | public String index() { 11 | return "index"; 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /src/main/java/com/datsystemz/nyakaz/springbootreactjsfullstack/exceptions/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.datsystemz.nyakaz.springbootreactjsfullstack.exceptions; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(value = HttpStatus.NOT_FOUND) 7 | public class ResourceNotFoundException extends RuntimeException{ 8 | public ResourceNotFoundException(String message){ 9 | super(message); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/datsystemz/nyakaz/springbootreactjsfullstack/models/User.java: -------------------------------------------------------------------------------- 1 | package com.datsystemz.nyakaz.springbootreactjsfullstack.models; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | 8 | @Entity 9 | public class User { 10 | 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.AUTO) 13 | private Long id; 14 | private String name; 15 | private String surname; 16 | private String email; 17 | private String username; 18 | private String password; 19 | 20 | protected User(){} 21 | 22 | public User(String name, String surname, String email, String username, String password){ 23 | this.name = name; 24 | this.surname = surname; 25 | this.email = email; 26 | this.username = username; 27 | this.password = password; 28 | } 29 | 30 | public Long getId(){ 31 | return id; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public String getSurname() { 39 | return surname; 40 | } 41 | 42 | public String getUsername() { 43 | return username; 44 | } 45 | 46 | public String getPassword() { 47 | return password; 48 | } 49 | 50 | public String getEmail() { 51 | return email; 52 | } 53 | 54 | public void setId(Long id) { 55 | this.id = id; 56 | } 57 | 58 | public void setName(String name) { 59 | this.name = name; 60 | } 61 | 62 | public void setSurname(String surname) { 63 | this.surname = surname; 64 | } 65 | 66 | public void setEmail(String email) { 67 | this.email = email; 68 | } 69 | 70 | public void setUsername(String username) { 71 | this.username = username; 72 | } 73 | 74 | public void setPassword(String password) { 75 | this.password = password; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/datsystemz/nyakaz/springbootreactjsfullstack/repositories/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.datsystemz.nyakaz.springbootreactjsfullstack.repositories; 2 | 3 | import com.datsystemz.nyakaz.springbootreactjsfullstack.models.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface UserRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/js/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import ReactDOM from "react-dom"; 3 | 4 | 5 | export class App extends Component { 6 | render() { 7 | return ( 8 |
9 |

Welcome to React Front End Served by Spring Boot

10 |
11 | ); 12 | } 13 | } 14 | 15 | export default App; 16 | 17 | ReactDOM.render(, document.querySelector("#app")); -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/main/resources/static/main.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyakaz73/spring-boot-reactjs-fullstack/cf532f8e4362fc2bb4d103a35d7b6f9cc606134f/src/main/resources/static/main.css -------------------------------------------------------------------------------- /src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ReactJS + Spring Data REST 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/test/java/com/datsystemz/nyakaz/springbootreactjsfullstack/SpringBootReactJsFullstackApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.datsystemz.nyakaz.springbootreactjsfullstack; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SpringBootReactJsFullstackApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/datsystemz/nyakaz/springbootreactjsfullstack/UserTests.java: -------------------------------------------------------------------------------- 1 | package com.datsystemz.nyakaz.springbootreactjsfullstack; 2 | 3 | import com.datsystemz.nyakaz.springbootreactjsfullstack.models.User; 4 | import com.datsystemz.nyakaz.springbootreactjsfullstack.repositories.UserRepository; 5 | import org.junit.Assert; 6 | import org.junit.jupiter.api.Test; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 9 | 10 | 11 | @DataJpaTest 12 | public class UserTests { 13 | 14 | @Autowired 15 | private UserRepository userRepository; 16 | 17 | @Test 18 | public void testSaveUser(){ 19 | User user = new User("John","Doe","john.doe@email.com","johhny","strong-password"); 20 | userRepository.save(user); 21 | userRepository.findById(new Long(1)) 22 | .map(newUser ->{ 23 | Assert.assertEquals("John",newUser.getName()); 24 | return true; 25 | }); 26 | } 27 | 28 | @Test 29 | public void getUser(){ 30 | User user = new User("John","Doe","john.doe@email.com","johhny","strong-password"); 31 | User user2 = new User("Daniel","Marcus","daniel@daniel.com","danie","super_strong_password"); 32 | userRepository.save(user); 33 | 34 | userRepository.save(user2); 35 | 36 | userRepository.findById(new Long(1)) 37 | .map(newUser ->{ 38 | Assert.assertEquals("danie",newUser.getUsername()); 39 | return true; 40 | }); 41 | 42 | } 43 | 44 | @Test 45 | public void getUsers(){ 46 | User user = new User("John","Doe","john.doe@email.com","johhny","strong-password"); 47 | User user2 = new User("Daniel","Marcus","daniel@daniel.com","danie","super_strong_password"); 48 | userRepository.save(user); 49 | userRepository.save(user2); 50 | 51 | Assert.assertNotNull(userRepository.findAll()); 52 | } 53 | 54 | @Test 55 | public void deleteUser(){ 56 | User user = new User("John","Doe","john.doe@email.com","johhny","strong-password"); 57 | userRepository.save(user); 58 | userRepository.delete(user); 59 | Assert.assertTrue(userRepository.findAll().isEmpty()); 60 | } 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | 3 | module.exports = { 4 | entry: './src/main/js/App.js', 5 | devtool: 'sourcemaps', 6 | cache: true, 7 | mode: 'development', 8 | output: { 9 | path: __dirname, 10 | filename: './src/main/resources/static/built/bundle.js' 11 | }, 12 | module: { 13 | rules: [ 14 | { 15 | test: path.join(__dirname, '.'), 16 | exclude: /(node_modules)/, 17 | use: [{ 18 | loader: 'babel-loader', 19 | options: { 20 | presets: ["@babel/preset-env", "@babel/preset-react"] 21 | } 22 | }] 23 | }, 24 | { 25 | test: /\.css$/, 26 | use: [ 27 | 'style-loader', 28 | 'css-loader' 29 | ] 30 | }, 31 | { 32 | test: /\.(png|svg|jpg|gif|eot|otf|ttf|woff|woff2)$/, 33 | use: [ 34 | { 35 | loader: 'url-loader', 36 | options: {} 37 | } 38 | ] 39 | } 40 | ] 41 | } 42 | }; --------------------------------------------------------------------------------