Commit 2696a080 by Patryk Czarnik

Alternatywne sposoby obsługi baz danych w Spring

parent 5c9f4b1f
package sklep.alternatywne_dostepy_do_bazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.sql.*;
@Controller
@RequestMapping("/alt0/products")
public class ProductController_v0 {
// W tej wersji samodzielnie nawiązuję połączenie z bazą
@GetMapping(produces = "text/plain;charset=UTF-8")
@ResponseBody
public String readAll() {
StringBuilder sb = new StringBuilder("Lista produktów:\n");
try(Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/sklep", "alx", "abc123");
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products ORDER BY product_id")) {
while(rs.next()) {
sb.append("* produkt ")
.append(rs.getString("product_name"))
.append(" za cenę ")
.append(rs.getBigDecimal("price"))
.append('\n');
}
} catch (SQLException e) {
e.printStackTrace();
sb.append("Błąd: ").append(e);
}
return sb.toString();
}
}
package sklep.alternatywne_dostepy_do_bazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.sql.DataSource;
import java.sql.*;
@Controller
@RequestMapping("/alt1/products")
public class ProductController_v1 {
@Autowired
private DataSource dataSource;
// W tej wersji Spring dostarcza nam obiekt DataSource na podstawie konfiguracji w pliku application.properties
@GetMapping(produces = "text/plain;charset=UTF-8")
@ResponseBody
public String readAll() {
StringBuilder sb = new StringBuilder("Lista produktów:\n");
try(Connection c = dataSource.getConnection();
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products ORDER BY product_id")) {
while(rs.next()) {
sb.append("* produkt ")
.append(rs.getString("product_name"))
.append(" za cenę ")
.append(rs.getBigDecimal("price"))
.append('\n');
}
} catch (SQLException e) {
e.printStackTrace();
sb.append("Błąd: ").append(e);
}
return sb.toString();
}
@GetMapping("/{id}")
@ResponseBody
public String jedenProdukt(@PathVariable int id) {
StringBuilder sb = new StringBuilder();
final String sql = "SELECT * FROM products WHERE product_id = ?";
try(Connection c = dataSource.getConnection();
PreparedStatement stmt = c.prepareStatement(sql)) {
stmt.setInt(1, id);
try(ResultSet rs = stmt.executeQuery()) {
if(rs.next()) {
sb.append("Znaleziony produkt:\n")
.append(rs.getString("product_name"))
.append(" za cenę ")
.append(rs.getBigDecimal("price"))
.append('\n');
} else {
sb.append("Nie ma produktu o numerze ").append(id);
}
}
} catch (SQLException e) {
e.printStackTrace();
sb.append("Błąd: " + e);
}
return sb.toString();
}
@GetMapping("/szukaj")
@ResponseBody
public String wyszukajProdukty(@RequestParam String name) {
StringBuilder sb = new StringBuilder();
final String sql = "SELECT * FROM products WHERE product_name = ? ORDER BY product_id";
try(Connection c = dataSource.getConnection();
PreparedStatement stmt = c.prepareStatement(sql)) {
stmt.setString(1, name);
try(ResultSet rs = stmt.executeQuery()) {
while(rs.next()) {
sb.append("* produkt ")
.append(rs.getString("product_name"))
.append(" za cenę ")
.append(rs.getBigDecimal("price"))
.append('\n');
}
}
} catch (SQLException e) {
e.printStackTrace();
sb.append("Błąd: " + e);
}
return sb.toString();
}
}
package sklep.alternatywne_dostepy_do_bazy;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import sklep.model.Product;
@Controller
@RequestMapping("/alt2/products")
public class ProductController_v2 {
@Autowired
private EntityManager em;
@GetMapping(produces = "text/plain;charset=UTF-8")
@ResponseBody
public String readAll() {
return em.createNamedQuery("Product.findAll", Product.class)
.getResultStream()
.map(product -> " * " + product.getProductName() + " za cenę " + product.getPrice() + "\n")
.collect(Collectors.joining());
}
@GetMapping(path = "/{id}", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String readOne(@PathVariable("id") Integer productId) {
Product product = em.find(Product.class, productId);
if(product != null) {
return product.getProductName() + " za cenę " + product.getPrice();
} else {
return "Nie ma produktu o numerze " + productId;
}
}
@GetMapping(path = "/szukaj", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String szukaj(String name) {
TypedQuery<Product> query = em.createQuery("SELECT p FROM Product p WHERE productName = :nazwa", Product.class);
query.setParameter("nazwa", name);
Product product = query.getSingleResult();
if(product != null) {
return product.getProductName() + " za cenę " + product.getPrice();
} else {
return "Nie ma produktu o nazwie " + name;
}
}
}
package sklep.alternatywne_dostepy_do_bazy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
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 org.springframework.web.bind.annotation.RequestMapping;
import sklep.model.Product;
import java.util.List;
@Controller
@RequestMapping("/alt3/products")
public class ProductController_v3 {
@Autowired
private EntityManager em;
@GetMapping
public String readAll(Model model) {
List<Product> products = em.createNamedQuery("Product.findAll", Product.class).getResultList();
model.addAttribute("products", products);
return "products";
}
@GetMapping("/{id}")
public String readOne(@PathVariable("id") Integer productId, Model model) {
Product product = em.find(Product.class, productId);
if(product != null) {
model.addAttribute("product", product);
return "product";
} else {
return "missing_product";
}
}
@GetMapping("/szukaj")
public String szukaj(String name, Model model) {
TypedQuery<Product> query = em.createQuery("SELECT p FROM Product p WHERE productName = :nazwa", Product.class);
query.setParameter("nazwa", name);
List<Product> products = query.getResultList();
model.addAttribute("products", products);
return "wyszukiwarka";
}
}
package sklep.alternatywne_dostepy_do_bazy;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sklep.model.Product;
@Controller
@RequestMapping("/alt4/products")
public class ProductController_v4 {
@Autowired
private ProductRepository_v4 productRepository;
@GetMapping
public String wszystkieProdukty(Model model) {
List<Product> products = productRepository.findAll();
model.addAttribute("products", products);
return "products";
}
@GetMapping("/{id}")
public String jedenProdukt(@PathVariable int id, Model model) {
Optional<Product> product = productRepository.findById(id);
if(product.isPresent()) {
model.addAttribute("product", product.get());
return "product";
} else {
model.addAttribute("product_id", id);
return "missing_product";
}
}
@GetMapping("/szukaj")
public String wyszukajProdukty(@RequestParam String name, Model model) {
List<Product> products = productRepository.findByProductName(name);
model.addAttribute("products", products);
return "products";
}
}
package sklep.alternatywne_dostepy_do_bazy;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sklep.model.Product;
@Controller
@RequestMapping("/alt5/products")
public class ProductController_v5 {
@Autowired
private ProductRepository_v5 productRepository;
@GetMapping
public String wszystkieProdukty(Model model) {
List<Product> products = productRepository.findAll();
model.addAttribute("products", products);
return "products";
}
@GetMapping("/{id}")
public String jedenProdukt(@PathVariable int id, Model model) {
Optional<Product> product = productRepository.findById(id);
if(product.isPresent()) {
model.addAttribute("product", product.get());
return "product";
} else {
model.addAttribute("product_id", id);
return "missing_product";
}
}
@GetMapping("/szukaj")
public String wyszukajProdukty(@RequestParam String name, Model model) {
List<Product> products = productRepository.findByProductName(name);
model.addAttribute("products", products);
return "products";
}
}
package sklep.alternatywne_dostepy_do_bazy;
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 org.springframework.web.bind.annotation.RequestMapping;
import sklep.model.Product;
@Controller
@RequestMapping("/alt6/products")
public class ProductController_v6 {
@Autowired
private ProductRepository_v6 productRepository;
@GetMapping
public String wszystkieProdukty(Model model) {
List<Product> products = productRepository.findAll();
model.addAttribute("products", products);
return "products";
}
@GetMapping("/{id}")
public String jedenProdukt(@PathVariable int id, Model model) {
Optional<Product> product = productRepository.findById(id);
if(product.isPresent()) {
model.addAttribute("product", product.get());
return "product";
} else {
model.addAttribute("product_id", id);
return "missing_product";
}
}
}
package sklep.alternatywne_dostepy_do_bazy;
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 org.springframework.web.bind.annotation.RequestMapping;
import sklep.model.Product;
import sklep.repository.ProductRepository;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
@Controller
@RequestMapping("/alt7/products")
public class ProductController_v7 {
@Autowired
private ProductRepository productRepository;
@GetMapping
public String readAll(Model model) {
List<Product> products = productRepository.findAll();
model.addAttribute("products", products);
return "products";
}
@GetMapping("/{id}")
public String readOne(@PathVariable("id") Integer productId, Model model) {
Optional<Product> product = productRepository.findById(productId);
if(product.isPresent()) {
model.addAttribute("product", product.get());
return "product";
} else {
return "missing_product";
}
}
@GetMapping("/szukaj")
public String szukaj(Model model,
String name,
BigDecimal min,
BigDecimal max) {
List<Product> products = List.of();
if(name != null && !name.isEmpty() && min == null && max == null) {
products = productRepository.findByProductNameContainingIgnoreCase(name);
} else if ((name == null || name.isEmpty()) && (min != null || max != null)) {
if(min == null) {
min = BigDecimal.ZERO;
}
if(max == null) {
max = BigDecimal.valueOf(1000_000_000);
}
products = productRepository.findByPriceBetween(min, max);
} else if (name != null && !name.isEmpty() && (min != null || max != null)) {
if(min == null) {
min = BigDecimal.ZERO;
}
if(max == null) {
max = BigDecimal.valueOf(1000_000_000);
}
products = productRepository.findByProductNameContainingIgnoringCaseAndPriceBetween(name, min, max);
}
model.addAttribute("products", products);
return "wyszukiwarka2";
}
}
package sklep.alternatywne_dostepy_do_bazy;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import sklep.model.Product;
@Repository
public class ProductRepository_v4 {
@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) {
return Optional.ofNullable(em.find(Product.class, productId));
}
public List<Product> findByProductName(String name) {
final String sql = "SELECT p FROM Product p WHERE p.productName = :name";
TypedQuery<Product> query = em.createQuery(sql, Product.class);
query.setParameter("name", name);
return query.getResultList();
}
}
package sklep.alternatywne_dostepy_do_bazy;
import java.util.List;
import java.util.Optional;
import sklep.model.Product;
public interface ProductRepository_v5 {
List<Product> findAll();
Optional<Product> findById(int productId);
List<Product> findByProductName(String name);
}
\ No newline at end of file
package sklep.alternatywne_dostepy_do_bazy;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import sklep.model.Product;
@Repository
public class ProductRepository_v5_Impl implements ProductRepository_v5 {
@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) {
return Optional.ofNullable(em.find(Product.class, productId));
}
public List<Product> findByProductName(String name) {
final String sql = "SELECT p FROM Product p WHERE p.productName = :name";
TypedQuery<Product> query = em.createQuery(sql, Product.class);
query.setParameter("name", name);
return query.getResultList();
}
}
package sklep.alternatywne_dostepy_do_bazy;
import org.springframework.data.jpa.repository.JpaRepository;
import sklep.model.Product;
// We wcześniejszych wersjach pisało się tu adnotację @Repository.
// @Repository
public interface ProductRepository_v6 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