Commit 3d3b3236 by Patryk Czarnik

Alternatywne sposoby dostepu do bazy danych

parent 58e55f1f
package sklep.alternatywne_wersje_bazy_danych;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ProductController_v1 {
@RequestMapping(path="/alt1/products", produces="text/plain")
@ResponseBody
public String wszystkieProdukty() {
StringBuilder sb = new StringBuilder();
try(Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/sklep", "kurs", "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: " + e);
}
return sb.toString();
}
}
package sklep.alternatywne_wersje_bazy_danych;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
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;
@Controller
@RequestMapping(path="/alt2/products", produces="text/plain")
public class ProductController_v2 {
@Autowired
private DataSource dataSource;
@GetMapping
@ResponseBody
public String wszystkieProdukty() {
StringBuilder sb = new StringBuilder();
final String sql = "SELECT * FROM products ORDER BY product_id";
try(Connection c = dataSource.getConnection();
PreparedStatement stmt = c.prepareStatement(sql);
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();
}
@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_wersje_bazy_danych;
import java.util.List;
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 jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import sklep.model.Product;
@Controller
@RequestMapping(path="/alt3/products", produces="text/plain")
public class ProductController_v3 {
@Autowired
private EntityManager em;
@GetMapping
@ResponseBody
public String wszystkieProdukty() {
StringBuilder sb = new StringBuilder();
TypedQuery<Product> query = em.createNamedQuery("Product.findAll", Product.class);
List<Product> products = query.getResultList();
for(Product product : products) {
sb.append("* produkt ")
.append(product.getProductName())
.append(" za cenę ")
.append(product.getPrice())
.append('\n');
}
return sb.toString();
}
@GetMapping("/{id}")
@ResponseBody
public String jedenProdukt(@PathVariable int id) {
StringBuilder sb = new StringBuilder();
Product product = em.find(Product.class, id);
if(product != null) {
sb.append("Znaleziony produkt:\n")
.append(product.getProductName())
.append(" za cenę ")
.append(product.getPrice())
.append('\n');
} else {
sb.append("Nie ma produktu o numerze ").append(id);
}
return sb.toString();
}
@GetMapping("/szukaj")
@ResponseBody
public String wyszukajProdukty(@RequestParam String name) {
StringBuilder sb = new StringBuilder();
final String sql = "SELECT p FROM Product p WHERE p.productName = :name";
TypedQuery<Product> query = em.createQuery(sql, Product.class);
query.setParameter("name", name);
List<Product> products = query.getResultList();
for(Product product : products) {
sb.append("* produkt ")
.append(product.getProductName())
.append(" za cenę ")
.append(product.getPrice())
.append('\n');
}
return sb.toString();
}
}
package sklep.alternatywne_wersje_bazy_danych;
import java.util.List;
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 jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import sklep.model.Product;
@Controller
@RequestMapping("/alt4/products")
public class ProductController_v4 {
@Autowired
private EntityManager em;
@GetMapping
public String wszystkieProdukty(Model model) {
TypedQuery<Product> query = em.createNamedQuery("Product.findAll", Product.class);
List<Product> products = query.getResultList();
model.addAttribute("products", products);
return "products";
}
@GetMapping("/{id}")
public String jedenProdukt(@PathVariable int id, Model model) {
Product product = em.find(Product.class, id);
if(product != null) {
model.addAttribute("product", product);
return "product";
} else {
model.addAttribute("product_id", id);
return "missing_product";
}
}
@GetMapping("/szukaj")
public String wyszukajProdukty(@RequestParam String name, Model model) {
final String sql = "SELECT p FROM Product p WHERE p.productName = :name";
TypedQuery<Product> query = em.createQuery(sql, Product.class);
query.setParameter("name", name);
List<Product> products = query.getResultList();
model.addAttribute("products", products);
return "products";
}
}
package sklep.alternatywne_wersje_bazy_danych;
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_wersje_bazy_danych;
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("/alt7/products")
public class ProductController_v7 {
@Autowired
private ProductRepository_v7 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_wersje_bazy_danych;
import java.math.BigDecimal;
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("/alt8")
public class ProductController_v8 {
@Autowired
private ProductRepository_v8 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 wyszukiwarka(Model model,
String name,
BigDecimal min,
BigDecimal max) {
List<Product> products = List.of();
if(name != null && !name.isEmpty() && min == null && max == null) {
products = productRepository.findByProductNameContainingIgnoringCase(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 "wyszukiwarka";
}
}
package sklep.alternatywne_wersje_bazy_danych;
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 {
@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_wersje_bazy_danych;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import sklep.model.Product;
@Repository
public interface ProductRepository_v7 extends JpaRepository<Product, Integer> {
}
package sklep.alternatywne_wersje_bazy_danych;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import sklep.model.Product;
@Repository
public interface ProductRepository_v8 extends JpaRepository<Product, Integer> {
List<Product> findByProductName(String name);
List<Product> findByProductNameContains(String name);
List<Product> findByProductNameContainingIgnoringCase(String name);
List<Product> findByPriceBetween(BigDecimal min, BigDecimal max);
List<Product> findByProductNameContainingIgnoringCaseAndPriceBetween(String name, BigDecimal min, BigDecimal max);
}
\ No newline at end of file
......@@ -44,11 +44,12 @@
<h2>Alternatywne dostępy do bazy danych</h2>
<ul>
<li><a href="/alt1/products">Dostęp JDBC</a> (klasyczne getConnection)</li>
<li><a href="/alt1/products/1">jeden produkt</a></li>
<li><a href="/alt1/products/szukaj?name=pralka">wg nazwy</a></li>
<li><a href="/alt2/products">Dostęp JDBC</a> (wstrzykiwanie DataSource)</li>
<li><a href="/alt2/products/1">jeden produkt</a></li>
<li><a href="/alt2/products/szukaj?name=pralka">wg nazwy</a></li>
<li><a href="/alt3/products">EntityManager</a> z poziomu Controllera</li>
<li><a href="/alt3/products/1">jeden produkt</a></li>
<li><a href="/alt3/products/szukaj?name=pralka">wg nazwy</a></li>
</ul>
</body>
</html>
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