spring mvc 的jpa JpaRepository資料層訪問

weixin_34148340發表於2019-01-29

1. Spring Data 應用場景

Spring Data包含多個子專案:
Spring Data JPA
Spring Data Mongo DB
Spring Data Redis
Spring Data Solr

2. JDBC和JPA的區別

Java資料庫連線,(Java Database Connectivity,簡稱JDBC)是Java語言中用來規範客戶端程式如何來訪問資料庫的應用程式介面,提供了諸如查詢和更新資料庫中資料的方法

JDBC: is a standard for Database Access (是Java的底層技術,包括也是很多database JPA的底層技術)
JPA: is a standard for ORM. This can "hide" the SQL from the developer so that all they deal with are Java classes, and the provider allows you to save them and load them magically. The most famous JPA provider is Hibernate

JDBC的一個例子:

    public String getAllEnglishWords() throws ClassNotFoundException, SQLException {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        Connection con = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1434;databaseName=DailyEnglish", "username", "password");
         Statement stmt = con.createStatement(); 
         ResultSet rs = stmt.executeQuery("select * from Words"); 
         //while(rs.next()) {
            // System.out.println(rs.getString("english"));
             //System.out.println(rs.getString("chinese"));
         //}
         String result = resultSetToJson(rs);
         System.out.println(result);
         rs.close();
         stmt.close();
         con.close();
        return result;
    }

3. Spring Data JPA

JPA (Java Persistence API)
ORM:Object-Relational Mapping: 讓你map entity class到sql table
Class <-> Table
當你用JAVA連線關係型資料庫事,你需要JDBC,並且執行queries,然後得到結果後,把它轉為物件;
References:
https://juejin.im/post/5aa9fb2a518825557e781bbf

相關文章