Commit 5dbcafeb by Patryk Czarnik

ProductRepository jako automatycznie tworzone JpaRepository

parent 3df0d996
package sklep.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import sklep.model.Product;
public interface ProductRepository {
/* Gdy w projekcie umieścimy interfejs rozszerzający interfejs JpaRepository (albo podobny)
* i oznaczymy go adnotacją @Repository (albo skonfigurujemy w inny sposób...),
* to Spring AUTOMATYCZNIE UTWORZY IMPLEMENTACJĘ tego interfejsu.
* Dzięki temu "za darmo" mamy metody dający podstawowy dostęp do tabel.
*/
List<Product> findAll();
Optional<Product> findById(int productId);
@Repository
public interface ProductRepository extends JpaRepository<Product, Integer> {
}
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 ProductRepositoryImpl implements ProductRepository {
@Autowired
private EntityManager em;
@Override
public List<Product> findAll() {
TypedQuery<Product> query = em.createNamedQuery("Product.findAll", Product.class);
return query.getResultList();
}
@Override
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