Commit f745cf05 by Patryk Czarnik

ProductRepository zaimplementowane samodzielnie

parent 5bffc4d1
package sklep.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import sklep.model.Product;
import sklep.repository.ProductRepository;
@Controller
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping("/products")
public String readAllProducts(Model model) {
List<Product> products = productRepository.findAll();
model.addAttribute("products", products);
return "products";
}
@GetMapping("/products/{id}")
public String readOneProduct(Model model, @PathVariable("id") int productId) {
Optional<Product> product = productRepository.findById(productId);
if(product.isPresent()) {
model.addAttribute("product", product.get());
}
return "product";
}
}
package sklep.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sklep.model.Product;
@Repository
public class ProductRepository {
@Autowired
private EntityManager em;
public List<Product> findAll() {
TypedQuery<Product> query = em.createNamedQuery("Product.findAll", Product.class);
return query.getResultList();
}
public Optional<Product> findById(int productId) {
Product product = em.find(Product.class, productId);
return Optional.ofNullable(product);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment