Commit c8e51acc by Patryk Czarnik

ProductRepository extends JpaRepository

parent 44b6cdeb
...@@ -8,28 +8,30 @@ import org.springframework.web.bind.annotation.GetMapping; ...@@ -8,28 +8,30 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import sklep.model.Product; import sklep.model.Product;
import sklep.repository.ProductRepository;
import java.util.List; import java.util.List;
import java.util.Optional;
@Controller @Controller
@RequestMapping("/products") @RequestMapping("/products")
public class ProductController { public class ProductController {
@Autowired @Autowired
private EntityManager em; private ProductRepository productRepository;
@GetMapping @GetMapping
public String readAll(Model model) { public String readAll(Model model) {
List<Product> products = em.createNamedQuery("Product.findAll", Product.class).getResultList(); List<Product> products = productRepository.findAll();
model.addAttribute("products", products); model.addAttribute("products", products);
return "products"; return "products";
} }
@GetMapping("/{id}") @GetMapping("/{id}")
public String readOne(@PathVariable("id") Integer productId, Model model) { public String readOne(@PathVariable("id") Integer productId, Model model) {
Product product = em.find(Product.class, productId); Optional<Product> product = productRepository.findById(productId);
if(product != null) { if(product.isPresent()) {
model.addAttribute("product", product); model.addAttribute("product", product.get());
return "product"; return "product";
} else { } else {
return "missing_product"; return "missing_product";
......
package sklep.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import sklep.model.Product;
public interface ProductRepository extends JpaRepository<Product, Integer> {
}
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