נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
JDBC ו-HttpClientJDBC & HttpClient
מפגש 39: מסד נתונים עם JDBC ו-SQL, PreparedStatement, וקריאות HTTP עם HttpClient.Session 39: A database with JDBC and SQL, PreparedStatement, and HTTP calls with HttpClient.
מסד נתונים עם JDBC ו-SQL, PreparedStatement, וקריאות HTTP עם HttpClient. בסוף המפגש מוסיפים צעד לפרויקט המלווה.A database with JDBC and SQL, PreparedStatement, and HTTP calls with HttpClient. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- JDBC עם PreparedStatementJDBC with PreparedStatement
- HttpClient מול שרת קטןHttpClient against a tiny server
- Repository: הנתונים מאחורי interfaceRepository: data behind an interface
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגש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:
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושא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.
חיבור, יצירת טבלה, הכנסה ושאילתה. כל ערך נכנס דרך ? ו-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.נושא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.
כדי להריץ באמת, התוכנית מרימה שרת 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.
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.נושאTopic 5
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository
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.JDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:JDBC: Java's standard way to talk to a database:
המונחים של המפגשThis session's termsSQL 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).
המונחים של המפגשThis session's termsRepository: interface שמסתיר איפה הנתונים נשמרים (save, findByAuthor).Repository: An interface hiding where data is kept (save, findByAuthor).
המונחים של המפגשThis session's termsHttpClient: HttpClient.newHttpClient() ו-client.send(request, BodyHandlers.ofString()):HttpClient: HttpClient.newHttpClient() and client.send(request, BodyHandlers.ofString()):
המונחים של המפגשThis session's termsקוד סטטוס: מספר בתשובת HTTP:status code: A number in an HTTP response:
המונחים של המפגשThis session's termsחיבור, יצירת טבלה, הכנסה ושאילתה.A connection, creating a table, an insert and a query.
JDBC עם PreparedStatementJDBC with PreparedStatementכל ערך נכנס דרך ? ו-setString/setInt, אף פעם לא בחיבור מחרוזות.Every value goes in through ? and setString/setInt, never by gluing strings.
JDBC עם PreparedStatementJDBC with PreparedStatementכל משאב נסגר ב-try-with-resources.Every resource closes in try-with-resources.
JDBC עם PreparedStatementJDBC with PreparedStatementכדי להריץ באמת, התוכנית מרימה שרת 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.
HttpClient מול שרת קטןHttpClient against a tiny serverהפלט אמיתי מזמן הבנייה.The output is real, from build time.
HttpClient מול שרת קטןHttpClient against a tiny servermain מדבר רק עם BookRepository.main talks only to BookRepository.
Repository: הנתונים מאחורי interfaceRepository: data behind an interfaceהיום המימוש בזיכרון; מחר JdbcBookRepository עם הקוד מהתזכורת הראשונה, בלי לשנות שורה ב-main.Today the implementation is in memory; tomorrow a JdbcBookRepository with the code from the first refresher, without changing a line of main.
Repository: הנתונים מאחורי interfaceRepository: data behind an interfaceמדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository
הצעד של היום בפרויקט מדףToday's step in the Shelf projectלמה "... 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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.קלט כמו ' OR '1'='1 משנה את השאילתהInput like ' OR '1'='1 changes the query
נכון: SQL injection.Right: SQL injection.מה הסטטוס כשהמשאב לא קיים?What's the status when the resource doesn't exist?
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.מה היתרון של 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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.אפשר להחליף את המימוש (מסד נתונים, זיכרון, בדיקות) בלי לשנות את מי שמשתמש בוYou can swap the implementation (database, memory, tests) without changing its users
נכון.Right.Repository בזיכרוןAn in-memory Repository
- כתבו
interface BookRepository (save, findByAuthor, findByTitle שמחזירה Optional) ומימוש InMemoryBookRepository.Write interface BookRepository (save, findByAuthor, findByTitle returning an Optional) and an InMemoryBookRepository.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: SQL injectionBug hunter: SQL injection
findQuery מחברת את הקלט לתוך ה-SQL, והקלט השני הופך את השאילתה ל"כל הספרים".findQuery glues the input into the SQL, and the second input turns the query into "every book".
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.לקרוא תשובת HTTPReading an HTTP response
- תשובת HTTP היא טקסט:An HTTP response is text:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.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.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 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.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.משורות לעצמיםFrom rows to objects
ResultSet הוא בעצם רשימת שורות.A ResultSet is really a list of rows.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.טרנזקציה: הכול או כלוםA transaction: all or nothing
TxRepo מדמה טרנזקציה:TxRepo imitates a transaction:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.המתודות במימוש חייבות public (הן מממשות interface).The implementing methods must be public (they implement an interface).
Repository בזיכרוןAn in-memory Repositoryזה בדיוק מה ש-PreparedStatement עושה: SQL קבוע, ערכים בנפרד.That's exactly what PreparedStatement does: fixed SQL, values separately.
צייד באגים: SQL injectionBug hunter: SQL injectionמה למדנו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
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.