Commit fcdb75d1 by Patryk Czarnik

Dostęp do bazy za pomocą JDBC

parent fa062879
package sklep.controller;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/alt1")
public class AlternatywneProdukty1 {
@Autowired
private DataSource dataSource;
// Tutaj użyjemy "zwykłego JDBC", czyli PreparedStatemnt, ResultSet itd...
// Ale Spring automatycznie wstrzyknie nam (jako DataSource) połączenie z bazą daych na podstawie konfiguracji.
@GetMapping(path="/products", produces="text/plain;charset=UTF-8")
@ResponseBody
public String products() {
final String sql = "SELECT product_name, price FROM products ORDER BY product_id";
try(Connection c = dataSource.getConnection();
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
StringBuilder tekst = new StringBuilder("Lista produktów:\n");
while(rs.next()) {
tekst.append(" * ");
tekst.append(rs.getString(1));
tekst.append(" za cenę ");
tekst.append(rs.getString(2));
tekst.append('\n');
}
return tekst.toString();
} catch (SQLException e) {
e.printStackTrace();
return "Problem z odczytaniem produktów: " + e;
}
}
}
......@@ -42,11 +42,10 @@
<h2>Alternatywne dostępy do bazy danych</h2>
<ul>
<li><a href="/dodatkowe/sql">Dostęp JDBC</a> (wstrzykiwanie DataSource)</li>
<li><a href="/dodatkowe/jpa">Dostęp Hibernate/JPA</a> (wstrzykiwanie EntityManager)</li>
<li><a href="/dodatkowe/products">products</a> (wstrzykiwanie EntityManager)</li>
<li><a href="/dodatkowe/products/1">jeden produkt</a></li>
<li><a href="/dodatkowe/by_price?min=1000&max=2900">by price</a></li>
<li><a href="/alt1/products">Dostęp JDBC</a> (wstrzykiwanie DataSource)</li>
<li><a href="/alt2/products">Dostęp Hibernate/JPA</a> (wstrzykiwanie EntityManager)</li>
<li><a href="/alt2/products/1">jeden produkt</a></li>
<li><a href="/alt2/products/by_price?min=1000&max=2900">by price</a></li>
</ul>
</body>
......
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