Skip to content

fefong/java-spring-boot-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java SpringBoot Application REST API - CRUD

Getting started with Java using SpringBoot Application - CRUD

Introduction

  • C - CREATE
  • R - READ
  • U - UPDATE
  • D - DELETE

Spring of modern applications, it is one of the main modern micro-service applications on top of Java, easy to develop and a tool with many possibilities

Stack Development:

  • Java 11 - SpringBoot Application
    • JPA
    • Lombok
  • MySQL Database

Database

Run database script.

Directory: ./assets/script-mysql-database.sql

Script: Database Structure

SpringBoot

Create new project Springboot Application.

Open file pom.xml add the dependencies;

⚠️ Open file example in project to see dependencies;

Rename file: application.properties to application.yml

Add configuration:

  • Server
server:
port: ${SERVER_PORT:9000}
  • Database
spring:
application:
  name: PROJECT-NAME
datasource:  
  url: ${DATASOURCE_URL}
  username: ${DATASOURCE_USERNAME}
  password: ${DATASOURCE_USERNAME}
  driver-class-name: ${DRIVER_CLASS_NAME:com.mysql.cj.jdbc.Driver}
  sql-script-encoding: UTF-8

See example: application.yml

Create Project Structure (Default)

  • Folder: .\src\main\java\com\ffong\demo\
    • config
      • Config.java

In the ..\src\main\java\com\ffong\demo\config\Config.java is possible add configurations for your service.

Use annotation: @Configurarion and implements interface: WebMvcConfigurer.

HTTP Methods - REST API

  • GET - list objects or return data/information only
  • POST - insert or method executon
  • PUT - update existing resource
  • DELETE - delete or soft-delete
  • PATH - to make partical update on a resource

⚠️ Important, descriptions are relative.

Override method addCorsMappings

@Override
public void addCorsMappings(CorsRegistry cors) {
    cors.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
}

ℹ️ add only methods necessary in your application.

See example: Config.java

Create Project Structure

  • Folder: .\src\main\java\com\ffong\demo\
    • client
      • controller
      • model
      • repository
      • service

Model

Create Model from object.

  • Folder: .\src\main\java\com\ffong\demo\

Add annotations:

  • @Entity
  • @Table(name = "TABLE_NAME")
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = false)
@Entity
@Table(name = "CLIENT")
public class Client {
// TODO
}

Import pom.xml dependencie Lombok add annotations lombook:

  • @AllArgsConstructor
  • @NoArgsConstructor
  • @Data
  • @EqualsAndHashCode(callSuper = false)

Using Lombok it will possible Generates an all-args constructor, a no-args constructor and Generates getters for all fields.

  • Add annotation: @Id in key table.

  • Add annotation: @Column(name = "COLUMN_NAME", nullable = false) in each field.

See example: Client Model

Repository

Create Interface Repository from object.

Add annotations:

  • @Repository
    @Repository
    public interface ClientRepository extends JpaRepository<Client, Long> {
    // TODO
    }

ℹ️ If your application used only basic finds not necessary create another's methods.

⚠️ JpaRepository< MODEL , TYPE OF ID >

See example: Client Repository

Service

Create Service from object.

Add annotations:

  • @Service
    @Service
    public class ClientServiceImpl implements ClientService {
    // TODO
    }

Usually two files are created:

  • Interface
    • The Interface can also be called IClient (I + Client).
  • Implementation Interface
    • Implement the interface above and add annotations.

Create methods in Interface(Client):

In the Implementation Interface(ClientServiceImpl.java):

  • Add methods from interface;
  • Set:
    @Autowired
    private ClientRepository clientRepository;
  • Method: List<Client> list():
    @Override
    public List<Client> list() {
    	List<Client> clients = new ArrayList<Client>();
    	clients = clientRepository.findAll();
    	return clients;
    }
  • Method: insert(Client client):
    @Override
    public Client insert(Client client) {
    	return clientRepository.save(client);
    }
  • Method: udpate(Long idClient, Client client):
    @Override
    public Client update(Long idClient, Client client) {
      Optional<Client> clientFind = clientRepository.findById(idClient);
      if (clientFind.isPresent()) {
        client.setId(idClient);
        return clientRepository.save(client);
      }
      return null;
    }
  • Method: delete(Long idClient):
    @Override
    public void delete(Long idClient) {
      clientRepository.deleteById(idClient);
    }

See example: Client Service - Interface

See example: Client Service - Implementation

Controller

Create Controller from object.

Add annotations:

  • @RestController

If you want you can configure a default path for all methods on this controller with: @RequestMapping("/client")

@RestController
@RequestMapping("/client")
public class ClientController {
// TODO
}

If the @RequestMapping is not configured it will be necessary to add it to each request.

Example:

@GetMapping(/client)
@PostMapping(/client) 
@PutMapping("/client/{idClient}")
@DeleteMapping("/client/{idClient}")
  • Set:

    @Autowired
    private ClientService clientService;
  • Method: List<Client> list():

    @GetMapping()
    public List<Client> list() {
    	return clientService.list();
    }

    @RequestMapping(method = RequestMethod.GET)

    @GetMapping: Annotation for mapping HTTP GET.

    • @GetMapping(): Get in path default "/".
    • @GetMapping("list"): Get in path: "/list".
  • Method: Client insert(@RequestBody Client client):

    @PostMapping()
    public Client insert(@RequestBody Client client) {
    	return clientService.insert(client);
    }

    @RequestMapping(method = RequestMethod.POST)

    @PostMapping: Annotation for mapping HTTP POST.

    • @PostMapping(): Get in path default "/".
    • @RequestBody Object o: necessary send body(JSON format);
  • Method: Client update(@PathVariable Long idClient, @RequestBody Client client):

    @PutMapping("/{idClient}")
    public Client update(@PathVariable Long idClient, @RequestBody Client client) {
    	return clientService.update(idClient, client);
    }

    @RequestMapping(method = RequestMethod.PUT)

    @PutMapping: Annotation for mapping HTTP PUT.

    • @PathVariable Long idClient: variable in path url add {idClient}.
    • @RequestBody Object o: necessary send body(JSON format);
  • Method: void delete(@PathVariable Long idClient):

    @DeleteMapping("/{idClient}")
    public void delete(@PathVariable Long idClient) {
    	clientService.delete(idClient);
    }

    @RequestMapping(method = RequestMethod.DELETE)

    @DeleteMapping: Annotation for mapping HTTP DELETE.

    • @PathVariable Long idClient: necessário variable in path add {idClient}.

See example: Client Controller

Some links for more in depth learning

About

Example using Java SpringBoot - REST API

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages