JDBC ו-HttpClientJDBC & HttpClient
מסד נתונים עם JDBC ו-SQL, PreparedStatement, וקריאות HTTP עם HttpClient.
A database with JDBC and SQL, PreparedStatement, and HTTP calls with HttpClient.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- JDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:
DriverManager.getConnection,PreparedStatement,ResultSet. כל מסד (PostgreSQL, MySQL, H2) מגיע עם driver משלו.JDBC: Java's standard way to talk to a database:DriverManager.getConnection,PreparedStatement,ResultSet. Each database (PostgreSQL, MySQL, H2) comes with its own driver. - SQL injection: כשמחברים קלט של משתמש לתוך מחרוזת SQL, הקלט יכול לשנות את השאילתה (
' OR '1'='1). פרמטרים (?) שולחים את הקלט בנפרד, כנתון ולא כקוד.SQL injection: When user input is glued into an SQL string, the input can change the query (' OR '1'='1). Parameters (?) send the input separately, as data and not as code. - Repository: interface שמסתיר איפה הנתונים נשמרים (
save,findByAuthor). מימוש אחד מדבר עם מסד נתונים, ואחר שומר בזיכרון לבדיקות.Repository: An interface hiding where data is kept (save,findByAuthor). One implementation talks to a database, another keeps it in memory for tests. - HttpClient:
HttpClient.newHttpClient()ו-client.send(request, BodyHandlers.ofString()): שולח בקשת HTTP ומחזירHttpResponseעםstatusCode(),headers()ו-body().HttpClient:HttpClient.newHttpClient()andclient.send(request, BodyHandlers.ofString()): sends an HTTP request and returns anHttpResponsewithstatusCode(),headers()andbody(). - קוד סטטוס: מספר בתשובת HTTP: 200 הצליח, 201 נוצר, 400 בקשה שגויה, 404 לא נמצא, 500 שגיאת שרת.status code: A number in an HTTP response: 200 OK, 201 created, 400 bad request, 404 not found, 500 server error.
02JDBC עם PreparedStatementJDBC with PreparedStatement
חיבור, יצירת טבלה, הכנסה ושאילתה. כל ערך נכנס דרך ? ו-setString/setInt, אף פעם לא בחיבור מחרוזות. כל משאב נסגר ב-try-with-resources.
A connection, creating a table, an insert and a query. Every value goes in through ? and setString/setInt, never by gluing strings. Every resource closes in try-with-resources.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws SQLException {
try (Connection db = DriverManager.getConnection("jdbc:h2:mem:shelf")) {
db.createStatement().execute("CREATE TABLE book (title VARCHAR(100), author VARCHAR(100), year INT)");
try (PreparedStatement insert = db.prepareStatement("INSERT INTO book VALUES (?, ?, ?)")) {
insert.setString(1, "Dune");
insert.setString(2, "Herbert");
insert.setInt(3, 1965);
insert.executeUpdate();
}
try (PreparedStatement q = db.prepareStatement("SELECT title, year FROM book WHERE author = ?")) {
q.setString(1, "Herbert");
try (ResultSet rs = q.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("title") + " " + rs.getInt("year"));
}
}
}
}
}
}להרצה במחשב שלכם: צריך driver של מסד נתונים (כאן H2), שמוסיפים כתלות ב-Maven. בסביבה של האתר אי אפשר להוריד אותו, ולכן הקוד מוצג בלי הרצה. הפלט הצפוי: Dune 1965.
Run it on your computer: it needs a database driver (H2 here), added as a Maven dependency. The site's build can't download it, so the code is shown without running. The expected output: Dune 1965.
03HttpClient מול שרת קטןHttpClient against a tiny server
כדי להריץ באמת, התוכנית מרימה שרת HTTP קטן על המחשב עצמו (HttpServer מה-JDK), ואז שולחת אליו בקשות עם HttpClient. הפלט אמיתי מזמן הבנייה.
To really run, the program starts a tiny HTTP server on the machine itself (HttpServer from the JDK), then sends it requests with HttpClient. The output is real, from build time.
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/books/1", ex -> {
byte[] body = "{\"title\": \"Dune\", \"year\": 1965}".getBytes();
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, body.length);
ex.getResponseBody().write(body);
ex.close();
});
server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort();
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create(base + "/books/1")).GET().build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode() + " " + res.headers().firstValue("Content-Type").orElse("?"));
System.out.println(res.body());
HttpResponse<String> missing = client.send(HttpRequest.newBuilder(URI.create(base + "/books/9")).build(), HttpResponse.BodyHandlers.ofString());
System.out.println(missing.statusCode());
server.stop(0);
}
}200 application/json
{"title": "Dune", "year": 1965}
40404Repository: הנתונים מאחורי interfaceRepository: data behind an interface
main מדבר רק עם BookRepository. היום המימוש בזיכרון; מחר JdbcBookRepository עם הקוד מהתזכורת הראשונה, בלי לשנות שורה ב-main.
main talks only to BookRepository. Today the implementation is in memory; tomorrow a JdbcBookRepository with the code from the first refresher, without changing a line of main.
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
BookRepository repo = new InMemoryBookRepository();
repo.save(new Book("Emma", "Austen", 1815));
repo.save(new Book("Dune", "Herbert", 1965));
repo.save(new Book("Persuasion", "Austen", 1817));
System.out.println(repo.findByAuthor("Austen"));
System.out.println(repo.findByTitle("Hamlet").isPresent());
}
}
interface BookRepository {
void save(Book b);
List<Book> findByAuthor(String author);
Optional<Book> findByTitle(String title);
}
record Book(String title, String author, int year) {
}
class InMemoryBookRepository implements BookRepository {
private final List<Book> rows = new ArrayList<>();
public void save(Book b) {
rows.add(b);
}
public List<Book> findByAuthor(String author) {
List<Book> out = new ArrayList<>();
for (Book b : rows) {
if (b.author().equals(author)) {
out.add(b);
}
}
return out;
}
public Optional<Book> findByTitle(String title) {
for (Book b : rows) {
if (b.title().equals(title)) {
return Optional.of(b);
}
}
return Optional.empty();
}
}[Book[title=Emma, author=Austen, year=1815], Book[title=Persuasion, author=Austen, year=1817]] false
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05הצעד של היום בפרויקט מדףToday's step in the Shelf project
ShelfService מקבל BookRepository בבנאי, דוחה שנה שלילית וכפולים, ושומר. הדפיסו saved Emma, rejected: duplicate, rejected: bad year, saved Persuasion, [Emma, Persuasion]. ב-JdbcBookRepository אמיתי הקוד של ShelfService לא ישתנה.
ShelfService takes a BookRepository in its constructor, rejects a negative year and duplicates, and saves. Print saved Emma, rejected: duplicate, rejected: bad year, saved Persuasion, [Emma, Persuasion]. With a real JdbcBookRepository, ShelfService's code won't change.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.