Commit 462f3052 by Patryk Czarnik

Controller używający EntityManager

parent 07041d27
package sklep.alternatywne_dostepy_do_bazy;
import jakarta.persistence.EntityManager;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sklep.model.Product;
import java.util.List;
@Controller
@RequestMapping("/products_v2")
public class ProductController_v2 {
@Autowired
private EntityManager em;
@GetMapping(produces = "text/plain;charset=UTF-8")
@ResponseBody
public String readAll() {
List<Product> products = em.createNamedQuery("Product.findAll", Product.class).getResultList();
StringBuilder sb = new StringBuilder("Lista produktów:\n");
for (Product product : products) {
sb.append(" * ")
.append(product.getProductName())
.append(" za cenę ")
.append(product.getPrice())
.append('\n');
}
return sb.toString();
}
}
package sklep.controller;
import jakarta.persistence.EntityManager;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sklep.model.Product;
import java.util.List;
import java.sql.*;
@Controller
@RequestMapping("/products")
public class ProductController {
@Autowired
private EntityManager em;
@GetMapping(produces = "text/plain;charset=UTF-8")
@ResponseBody
public String readAll() {
List<Product> products = em.createNamedQuery("Product.findAll", Product.class).getResultList();
StringBuilder sb = new StringBuilder("Lista produktów:\n");
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"))
for (Product product : products) {
sb.append(" * ")
.append(product.getProductName())
.append(" za cenę ")
.append(rs.getBigDecimal("price"))
.append(product.getPrice())
.append('\n');
}
} catch (SQLException e) {
e.printStackTrace();
sb.append("Błąd: " + e);
}
return sb.toString();
}
}
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