Code Monkey home page Code Monkey logo

aulao005's Introduction

Seu primeiro projeto Java web no Spring Boot - Aulão #005

DevSuperior - sua carreira dev com fundamento de ensino superior

Comunidade no Discord: https://discord.gg/SbjpsFv

Não perca as novidades:

Assista o vídeo desta aula:

Image

Sumário

O que você vai aprender

  • Criar um simples projeto Java web no Spring Boot e Maven
  • Introdução prática a injeção de dependência no Spring Boot
  • Introdução prática a REST / web services
  • Introdução prática ao Spring Data JPA com banco H2

Links sobre REST

Pré-requisitos

Passos

  • Criar projeto Maven usando Spring Initializr e importar no STS

  • Sugestão: acrescentar no .gitignore:

.DS_Store
.vscode
.metadata
.mvn

mvnw
mvnw.cmd
  • Criar a entidade Category

  • Criar CategoryResource

@RestController
@RequestMapping(value = "/categories")
public class CategoryResource {

	@GetMapping
	public ResponseEntity<...> findAll() {
		...
		return ResponseEntity.ok().body(...);
	}

	@GetMapping(value = "/{id}")
	public ResponseEntity<...> findById(@PathVariable Long id) {
		...
		return ResponseEntity.ok().body(...);
	}
}
  • Criar CategoryRepository
@Component
public class CategoryRepository {

	public void save(Category obj) {
		...
	}

	public Category findById(Long id) {
		...
	}
	
	public List<Category> findAll() {
		...
	}
}
  • Implementar CommandLineRunner para instanciar categorias no startup da aplicação. Usar o mecanismo de injeção de dependência do Spring Boot para obter uma instância de CategoryRepository.
Category cat1 = new Category(1L, "Electronics");
Category cat2 = new Category(2L, "Books");
  • Opcional: salvar um commit

  • Acrescentar entidade Product ao projeto

Category cat1 = new Category(1L, "Electronics");
Category cat2 = new Category(2L, "Books");

Product p1 = new Product(1L, "TV", 2200.00, cat1);
Product p2 = new Product(2L, "Domain Driven Design", 120.00, cat2);
Product p3 = new Product(3L, "PS5", 2800.00, cat1);
Product p4 = new Product(4L, "Docker", 100.00, cat2);

cat1.getProducts().addAll(Arrays.asList(p1, p3));
cat2.getProducts().addAll(Arrays.asList(p2, p4));
  • Opcional: salvar um commit

  • Acrescentar as dependências Maven de Spring Data JPA e banco H2

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>
  • Acrescentar as configurações do H2 em application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
  • Fazer os mapeamentos objeto-relacional
@Entity
public class Product implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	private String name;
	private Double price;
	
	@ManyToOne
	@JoinColumn(name = "category_id")
	private Category category;
  • Retirar os ID's das instâncias em CommandLineRunner (deixar como null)

  • Trocar o código dos repositories: usar JpaRepository<Entity, ID>

  • Fim: salvar um commit

Diagramas

Modelo conceitual

myImage

Instância

myImage

aulao005's People

Contributors

acenelio avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.