Olá estou com um problema que não consegui resolver com nenhuma das resoluções ja apresentadas. É meu primeiro projeto em JAVA então muitos conceitos são novos para mim.
Quando vou dar o start na aplicação aparece esse erro abaixo.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.7)
2023-01-18 19:35:09.810 INFO 84697 --- [ main] c.a.p.PeopleManagerApplication : Starting PeopleManagerApplication using Java 11.0.17 on deivid-developer with PID 84697 (/media/deivid/394080B278DBED9A26/DesafioAttornatus/people-manager/target/classes started by deivid in /media/deivid/394080B278DBED9A26/DesafioAttornatus/people-manager)
2023-01-18 19:35:09.814 INFO 84697 --- [ main] c.a.p.PeopleManagerApplication : No active profile set, falling back to 1 default profile: "default"
2023-01-18 19:35:10.559 INFO 84697 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-01-18 19:35:10.620 INFO 84697 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 52 ms. Found 2 JPA repository interfaces.
2023-01-18 19:35:11.387 INFO 84697 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-01-18 19:35:11.398 INFO 84697 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-01-18 19:35:11.398 INFO 84697 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.70]
2023-01-18 19:35:11.480 INFO 84697 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-01-18 19:35:11.480 INFO 84697 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1587 ms
2023-01-18 19:35:11.516 INFO 84697 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-01-18 19:35:11.738 INFO 84697 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-01-18 19:35:11.751 INFO 84697 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2'. Database available at 'jdbc:h2:mem:peopleManagerDb'
2023-01-18 19:35:11.857 WARN 84697 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addressesController': Unsatisfied dependency expressed through field 'addressesService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addressesService': Unsatisfied dependency expressed through field 'addressesRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addressesRepository' defined in com.api.peoplemanager.repository.AddressesRepository defined in @EnableJpaRepositories declared on PeopleManagerApplication: Cannot create inner bean '(inner bean)#666618d6' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#666618d6': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2023-01-18 19:35:11.858 INFO 84697 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2023-01-18 19:35:11.860 INFO 84697 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2023-01-18 19:35:11.863 INFO 84697 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2023-01-18 19:35:11.872 INFO 84697 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-01-18 19:35:11.891 ERROR 84697 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field addressesRepository in com.api.peoplemanager.service.AddressesService required a bean named 'entityManagerFactory' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
Process finished with exit code 1
Classe principal
package com.api.peoplemanager;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories
public class PeopleManagerApplication {
public static void main(String[] args) {
SpringApplication.run(PeopleManagerApplication.class, args);
}
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setSkipNullEnabled(true);
return modelMapper;
}
}
Entidade Addresses
package com.api.peoplemanager.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Data // criar getter e setter e o toString
@AllArgsConstructor // cria construtor com as propriedades de endereço
@NoArgsConstructor // cria construtor vazio
@Builder // ajudar na criação de objetos endereço
@Entity // informar que é uma entidade do BD
public class Addresses implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "publicPlace", nullable = false)
private String publicPlace;
@Column(name = "zipCode", nullable = false)
private String zipCode;
@Column(name = "number", nullable = false)
private String number;
@Column(name = "city", nullable = false)
private String city;
}
Entidade People
package com.api.peoplemanager.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Data // criar getter e setter e o toString
@AllArgsConstructor // cria construtor com as propriedades de pessoa
@NoArgsConstructor // cria construtor vazio
@Builder // ajudar na criação de objetos pessoa
@Entity // informar que é uma entidade do BD
public class People implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "birthDate", nullable = false)
private String birthDate;
@Column(name = "addressId", nullable = false)
private String addressId;
}
Repositório Addresses
package com.api.peoplemanager.repository;
import com.api.peoplemanager.entity.Addresses;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AddressesRepository extends JpaRepository<Addresses, Long> {
}
Repositório People
package com.api.peoplemanager.repository;
import com.api.peoplemanager.entity.People;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PeopleRepository extends JpaRepository<People, Long> {
}
AddressService
package com.api.peoplemanager.service;
import com.api.peoplemanager.entity.Addresses;
import com.api.peoplemanager.repository.AddressesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class AddressesService {
@Autowired
private AddressesRepository addressesRepository;
public Addresses salvar(Addresses addresses) {
return addressesRepository.save(addresses);
}
public List<Addresses> listAddresses() {
return addressesRepository.findAll();
}
public Optional<Addresses> searchById(Long id) {
return addressesRepository.findById(id);
}
public void removeById(Long id) {
addressesRepository.deleteById(id);
}
}
PeopleService
package com.api.peoplemanager.service;
import com.api.peoplemanager.entity.People;
import com.api.peoplemanager.repository.PeopleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class PeopleService {
@Autowired
private PeopleRepository peopleRepository;
public People salvar(People people) {
return peopleRepository.save(people);
}
public List<People> listPeople() {
return peopleRepository.findAll();
}
public Optional<People> searchById(Long id) {
return peopleRepository.findById(id);
}
public void removeById(Long id) {
peopleRepository.deleteById(id);
}
}
Address controller
package com.api.peoplemanager.http.controller;
import com.api.peoplemanager.entity.Addresses;
import com.api.peoplemanager.service.AddressesService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@RestController
@RequestMapping("/address")
public class AddressesController {
@Autowired
private AddressesService addressesService;
@Autowired
private ModelMapper modelMapper;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Addresses salvar(@RequestBody Addresses addresses) {
return addressesService.salvar(addresses);
}
@GetMapping
@ResponseStatus(HttpStatus.OK)
public List<Addresses> listAddresses() {
return addressesService.listAddresses();
}
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
public Addresses searchAddressById(@PathVariable("id") Long id) {
return addressesService.searchById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Endereço não encontrado"));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removeAddress(@PathVariable("id") Long id) {
addressesService.searchById(id)
.map(address -> {
addressesService.removeById(address.getId());
return Void.TYPE;
}).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Endereço não encontrado"));
}
@PutMapping("{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateAddress(@PathVariable("id") Long id, @RequestBody Addresses addresses) {
addressesService.searchById(id)
.map(addressesBase -> {
modelMapper.map(addresses, addressesBase);
addressesService.salvar(addressesBase);
return Void.TYPE;
}).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Endereço não encontrado"));
}
}
People controller
package com.api.peoplemanager.http.controller;
import com.api.peoplemanager.entity.People;
import com.api.peoplemanager.service.PeopleService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@RestController
@RequestMapping("/people")
public class PeopleController {
@Autowired
private PeopleService peopleService;
@Autowired
private ModelMapper modelMapper;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public People salvar(@RequestBody People people) {
return peopleService.salvar(people);
}
@GetMapping
@ResponseStatus(HttpStatus.OK)
public List<People> listPeople() {
return peopleService.listPeople();
}
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
public People searchPeopleById(@PathVariable("id") Long id) {
return peopleService.searchById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pessoa não encontrada"));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removePeople(@PathVariable("id") Long id) {
peopleService.searchById(id)
.map(people -> {
peopleService.removeById(people.getId());
return Void.TYPE;
}).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pessoa não encontrada"));
}
@PutMapping("{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updatePeople(@PathVariable("id") Long id, @RequestBody People people) {
peopleService.searchById(id)
.map(peopleBase -> {
modelMapper.map(people, peopleBase);
peopleService.salvar(peopleBase);
return Void.TYPE;
}).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pessoa não encontrada"));
}
}