Please enable JavaScript.
Coggle requires JavaScript to display documents.
Java Spring MVC & Spring Boot (Write API with Spring Boot Application)…
Java Spring MVC & Spring Boot
Write API with Spring Boot Application
Open Spring Initializer, generate Maven/Gradle Project
Add basic dependencies: JPA, Spring MVC,...
models
Database <=> Models
Properties with anotations
Entity
public class User {
...private
Id
GeneratedValue
Long id;
//getter, setter
repositories
public interface UserRepository extends JpaRepository<User, Long> {...}
Initialize data
(Code First)
Configuration
public class Database {
Bean
CommandLineRunner initDatabase(UserRepository repository){
//creates object and implements interface CommandLineRunner ...
Find with "try-catch":
repository.findById(id)
.orElseThrow(() -> new Exception("Cannot find user"));
Insert:
repository.save(newUser)
Update:
repository.findById(id)
.map(user -> {
user.setEmail(newUser.getEmail());//...
}).orElseGet(() -> {
newUser.setId(id);
});
Delete
repository.deleteById(id);
controllers
RestController
public class UserController {...}
//Dependency Injection:
private final UserRepository repository;
public UserController(UserRepository repository) {...}
Rest methods: GET, POST, PUT, DELETE
GET method
get method with route:
GetMapping("/users/{id}")
User
findById(@PathVariable
Long id) {...}
POST, PUT, DELETE
POST method:
PostMapping("/registerUser")
User
registerUser(@RequestBody
User newUser) {...}
//Postman => Body, Raw, JSON
PUT method:
PutMapping("/users/{id}")
User
updateUser(@RequestBody
User newUser,
PathVariable
Long id) {...}
DELETE method:
DeleteMapping("/users/{id}")
void
deleteEmployee(@PathVariable
Long id) {...}
Name: Nguyen Duc Hoang
Youtube:
https://www.youtube.com/c/nguyenduchoang