durante a pratica do desafio, encontrei a seguinte exceção:java.lang.NullPointerException: Cannot invoke "com.example.gerenciador_pedidos.repository.CategoryRepository.saveAll(java.lang.Iterable)" because "this.categoryRepository" is null
a exceção redireciona a causa para a classe Main:
//Main
@Component
public class Main {
@Autowired
private ProductRepository productRepository;
@Autowired
private CategoryRepository categoryRepository;
public void Main() {
Category eletronics = new Category(1L, "Eletronics");
Category tools = new Category(2L, "Tools");
Product notebook = new Product(4500.0,"Notebook", eletronics);
Product smartphone = new Product(2500.0, "Smartphone", eletronics);
Product watch = new Product(750.0, "Watch", eletronics);
Product powerScrewdriver = new Product(300.0, "Power Screwdriver", tools);
eletronics.setProduct(List.of(notebook, smartphone, watch));
tools.setProduct(List.of(powerScrewdriver));
categoryRepository.saveAll(List.of(eletronics, tools));
System.out.println("Categorias e produtos: ");
categoryRepository.findAll().forEach(category -> {
System.out.println("Categorias: " + category.getName());
category.getProduct().forEach(product -> System.out.println("Produtos: " + product.getName()));
});
// Requests requests = new Requests(1L, LocalDate.now());
}
}
//modelos:
@Entity
public class Category {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
private List<Product> product;
public Category(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
public Category() {
}
}
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String name;
@Column(name = "value")
private double price;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
public Product(double price, String name, Category category) {
this.price = price;
this.name = name;
this.category = category;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public Category getCategory() {
return category;
}
public Product() {
}
}
//Repositórios:
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {}
@Repository
public interface CategoryRepository extends JpaRepository<Category, Long> {}