一、簡介
第一章介紹了spring boot簡單入門,這一章介紹一下如何通過springDataJPA快速實現DAO層開發。
二、環境
1. jdk1.8
2. springboot 1.5.9.RELEASE
3. apache maven(3.5.0)
4. 開發工具(IntelliJ IDEA )
三、步驟
1)通過idea file->new project->Spring Initializr 創建項目,選中web->web,sql->JPA、MySQL。
2)創建項目,修改pom中依賴為 springboot 1.5.9.RELEASE(這個是我常用版本,可修改)、添加druid數據庫連接池,spring boot是通過各種starter+AutoConfiguration幫我們簡化配置。
<dependencies> <!-- 數據庫連接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.25</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
3)實體類、JPA接口,測試類,配置文件。
注意需要給一個默認的構造方法
通過這個測試案例,我們簡單模擬了JPA的增、刪、改、查功能,然后關聯查詢、指定字段查詢也是支持的,這里不做過多介紹,需要打印sql時在配置文件中開啟showsql屬性為true即可,下圖為運行結果。
四、總結
通過springDataJPA讓我們感受到了開發DAO層的方便,有興趣的話可以研究一些復雜用法,之前我們通常使用重SQL模式,很多業務邏輯都放在了一條SQL中去幫我們實現,遇到復雜SQL調優起來就會變的很麻煩,通過JPA我們可以嘗試一下輕SQL重JAVA代碼的形式。
源碼地址 https://github.com/binary-vi/binary.github.io/tree/master/SpringBoot-demo/demo02