נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
JavaJava

JDBC ו-HttpClientJDBC & HttpClient

מפגש 39: מסד נתונים עם JDBC ו-SQL, PreparedStatement, וקריאות HTTP עם HttpClient.Session 39: A database with JDBC and SQL, PreparedStatement, and HTTP calls with HttpClient.

מה נעשה היוםToday's plan

  • מונחיםTerms
  • JDBC עם PreparedStatementJDBC with PreparedStatement
  • HttpClient מול שרת קטןHttpClient against a tiny server
  • Repository: הנתונים מאחורי interfaceRepository: data behind an interface
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

המונחים של המפגשThis session's terms

  • JDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:JDBC: Java's standard way to talk to a database:
  • 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).
  • Repository: interface שמסתיר איפה הנתונים נשמרים (save, findByAuthor).Repository: An interface hiding where data is kept (save, findByAuthor).
  • HttpClient: HttpClient.newHttpClient() ו-client.send(request, BodyHandlers.ofString()):HttpClient: HttpClient.newHttpClient() and client.send(request, BodyHandlers.ofString()):
  • קוד סטטוס: מספר בתשובת HTTP:status code: A number in an HTTP response:
נושאTopic 2

JDBC עם PreparedStatementJDBC with PreparedStatement

JDBC עם PreparedStatementJDBC with PreparedStatement

  • חיבור, יצירת טבלה, הכנסה ושאילתה.A connection, creating a table, an insert and a query.
  • כל ערך נכנס דרך ? ו-setString/setInt, אף פעם לא בחיבור מחרוזות.Every value goes in through ? and setString/setInt, never by gluing strings.
  • כל משאב נסגר ב-try-with-resources.Every resource closes in try-with-resources.
נושאTopic 3

HttpClient מול שרת קטןHttpClient against a tiny server

HttpClient מול שרת קטן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.
נושאTopic 4

Repository: הנתונים מאחורי interfaceRepository: data behind an interface

Repository: הנתונים מאחורי interfaceRepository: data behind an interface

  • main מדבר רק עם BookRepository.main talks only to BookRepository.
  • היום המימוש בזיכרון; מחר JdbcBookRepository עם הקוד מהתזכורת הראשונה, בלי לשנות שורה ב-main.Today the implementation is in memory; tomorrow a JdbcBookRepository with the code from the first refresher, without changing a line of main.
נושאTopic 5

פרויקט מדףShelf project

הצעד של היום בפרויקט מדףToday's step in the Shelf project

  • מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository

JDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:JDBC: Java's standard way to talk to a database:

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).

Repository: interface שמסתיר איפה הנתונים נשמרים (save, findByAuthor).Repository: An interface hiding where data is kept (save, findByAuthor).

HttpClient: HttpClient.newHttpClient() ו-client.send(request, BodyHandlers.ofString()):HttpClient: HttpClient.newHttpClient() and client.send(request, BodyHandlers.ofString()):

קוד סטטוס: מספר בתשובת HTTP:status code: A number in an HTTP response:

חיבור, יצירת טבלה, הכנסה ושאילתה.A connection, creating a table, an insert and a query.

כל ערך נכנס דרך ? ו-setString/setInt, אף פעם לא בחיבור מחרוזות.Every value goes in through ? and setString/setInt, never by gluing strings.

כל משאב נסגר ב-try-with-resources.Every resource closes in try-with-resources.

כדי להריץ באמת, התוכנית מרימה שרת 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.

main מדבר רק עם BookRepository.main talks only to BookRepository.

היום המימוש בזיכרון; מחר JdbcBookRepository עם הקוד מהתזכורת הראשונה, בלי לשנות שורה ב-main.Today the implementation is in memory; tomorrow a JdbcBookRepository with the code from the first refresher, without changing a line of main.

מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository

למה "... WHERE author = '" + input + "'" מסוכן?Why is "... WHERE author = '" + input + "'" dangerous?

  • קלט כמו ' OR '1'='1 משנה את השאילתהInput like ' OR '1'='1 changes the query
  • זה איטיIt's slow
  • זה לא מתקמפלIt doesn't compile
  • אין בעיהNo problem

קלט כמו ' OR '1'='1 משנה את השאילתהInput like ' OR '1'='1 changes the query

מה הסטטוס כשהמשאב לא קיים?What's the status when the resource doesn't exist?

  • 404404
  • 200200
  • 500500
  • 201201

404404

מה היתרון של BookRepository כ-interface?What's the benefit of BookRepository as an interface?

  • אפשר להחליף את המימוש (מסד נתונים, זיכרון, בדיקות) בלי לשנות את מי שמשתמש בוYou can swap the implementation (database, memory, tests) without changing its users
  • הוא מהיר יותרIt's faster
  • JDBC דורשJDBC requires it
  • אין יתרוןNo benefit

אפשר להחליף את המימוש (מסד נתונים, זיכרון, בדיקות) בלי לשנות את מי שמשתמש בוYou can swap the implementation (database, memory, tests) without changing its users

Repository בזיכרוןAn in-memory Repository

  • כתבו interface BookRepository (save, findByAuthor, findByTitle שמחזירה Optional) ומימוש InMemoryBookRepository.Write interface BookRepository (save, findByAuthor, findByTitle returning an Optional) and an InMemoryBookRepository.

צייד באגים: SQL injectionBug hunter: SQL injection

  • findQuery מחברת את הקלט לתוך ה-SQL, והקלט השני הופך את השאילתה ל"כל הספרים".findQuery glues the input into the SQL, and the second input turns the query into "every book".

לקרוא תשובת HTTPReading an HTTP response

  • תשובת HTTP היא טקסט:An HTTP response is text:

Optional מה-RepositoryOptional from the Repository

  • עם findByTitle (מחזירה Optional<Book>) הדפיסו Dune (1965) | not found, בלי null ובלי if.With findByTitle (returning an Optional<Book>) print Dune (1965) | not found, with no null and no if.

מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository

  • ShelfService מקבל BookRepository בבנאי, דוחה שנה שלילית וכפולים, ושומר.ShelfService takes a BookRepository in its constructor, rejects a negative year and duplicates, and saves.

משורות לעצמיםFrom rows to objects

  • ResultSet הוא בעצם רשימת שורות.A ResultSet is really a list of rows.

טרנזקציה: הכול או כלוםA transaction: all or nothing

  • TxRepo מדמה טרנזקציה:TxRepo imitates a transaction:

המתודות במימוש חייבות public (הן מממשות interface).The implementing methods must be public (they implement an interface).

זה בדיוק מה ש-PreparedStatement עושה: SQL קבוע, ערכים בנפרד.That's exactly what PreparedStatement does: fixed SQL, values separately.

מה למדנוWhat we learned

  • JDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:JDBC: Java's standard way to talk to a database:
  • חיבור, יצירת טבלה, הכנסה ושאילתה.A connection, creating a table, an insert and a query.
  • כדי להריץ באמת, התוכנית מרימה שרת 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.
  • main מדבר רק עם BookRepository.main talks only to BookRepository.
  • מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

נבנה על ידיBuilt by Ariel Yohimovich