參考官方例子:https://spring.io/guides/gs/accessing-data-jpa/
接著上篇內容
一、小試牛刀
建立maven專案後,修改pom.xml檔案
![](https://i.iter01.com/images/86153736c3d440f2e7d2df2432d97112d2ef05f0cb7522cf2307c3de9447249a.gif)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.carter659</groupId> <artifactId>spring05</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> </parent> <name>spring05</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
多引入了JPA的依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
src/main/resources/application.properties和src/main/resources/templates/index.html保持上篇不變:
![](https://i.iter01.com/images/86153736c3d440f2e7d2df2432d97112d2ef05f0cb7522cf2307c3de9447249a.gif)
spring.datasource.initialize=false spring.datasource.url=jdbc:mysql://localhost:3306/demo spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.jdbc.Driver
![](https://i.iter01.com/images/86153736c3d440f2e7d2df2432d97112d2ef05f0cb7522cf2307c3de9447249a.gif)
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>玩轉spring boot——結合JPA</title> <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script> <script type="text/javascript"> /*<![CDATA[*/ var app = angular.module('app', []); app.controller('MainController', function($rootScope, $scope, $http) { $scope.data = {}; $scope.rows = []; //新增 $scope.add = function() { $scope.data = { no : 'No.1234567890', quantity : 100, 'date' : '2016-12-30' }; } //編輯 $scope.edit = function(id) { for ( var i in $scope.rows) { var row = $scope.rows[i]; if (id == row.id) { $scope.data = row; return; } } } //移除 $scope.remove = function(id) { for ( var i in $scope.rows) { var row = $scope.rows[i]; if (id == row.id) { $scope.rows.splice(i, 1); return; } } } //儲存 $scope.save = function() { $http({ url : '/save', method : 'POST', data : $scope.data }).success(function(r) { //儲存成功後更新資料 $scope.get(r.id); }); } //刪除 $scope.del = function(id) { $http({ url : '/delete?id=' + id, method : 'POST', }).success(function(r) { //刪除成功後移除資料 $scope.remove(r.id); }); } //獲取資料 $scope.get = function(id) { $http({ url : '/get?id=' + id, method : 'POST', }).success(function(data) { for ( var i in $scope.rows) { var row = $scope.rows[i]; if (data.id == row.id) { row.no = data.no; row.date = data.date; row.quantity = data.quantity; return; } } $scope.rows.push(data); }); } //初始化載入資料 $http({ url : '/findAll', method : 'POST' }).success(function(rows) { for ( var i in rows) { var row = rows[i]; $scope.rows.push(row); } }); }); /*]]>*/ </script> </head> <body ng-app="app" ng-controller="MainController"> <h1>玩轉spring boot——結合JPA</h1> <h4> <a href="http://www.cnblogs.com/GoodHelper/">from 劉冬的部落格</a> </h4> <input type="button" value="新增" ng-click="add()" /> <input type="button" value="儲存" ng-click="save()" /> <br /> <br /> <h3>清單資訊:</h3> <input id="id" type="hidden" ng-model="data.id" /> <table cellspacing="1" style="background-color: #a0c6e5"> <tr> <td>編號:</td> <td><input id="no" ng-model="data.no" /></td> <td>日期:</td> <td><input id="date" ng-model="data.date" /></td> <td>數量:</td> <td><input id="quantity" ng-model="data.quantity" /></td> </tr> </table> <br /> <h3>清單列表:</h3> <table cellspacing="1" style="background-color: #a0c6e5"> <tr style="text-align: center; COLOR: #0076C8; BACKGROUND-COLOR: #F4FAFF; font-weight: bold"> <td>操作</td> <td>編號</td> <td>日期</td> <td>數量</td> </tr> <tr ng-repeat="row in rows" bgcolor='#F4FAFF'> <td><input ng-click="edit(row.id)" value="編輯" type="button" /><input ng-click="del(row.id)" value="刪除" type="button" /></td> <td>{{row.no}}</td> <td>{{row.date}}</td> <td>{{row.quantity}}</td> </tr> </table> <br /> <a href="http://www.cnblogs.com/GoodHelper/">點選訪問原版部落格</a> </body> </html>
修改上篇的“Order.java”類:
package com.github.carter659.spring05; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.GenericGenerator; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ @Entity @Table(name = "t_order") public class Order { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") @Column(name = "order_id", length = 36) public String id; @Column(name = "order_no", length = 50) public String no; @Temporal(TemporalType.DATE) @Column(name = "order_date") public Date date; @Column(name = "quantity") public int quantity; /** * 省略 get set */ }
新建“OrderRepository.java”檔案
package com.github.carter659.spring05; import org.springframework.data.jpa.repository.JpaRepository; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ public interface OrderRepository extends JpaRepository<Order, String> { }
這個類實現了JpaRepository<>介面,此介面附帶常用的增刪改查到方法。
修改上篇的控制器“MainController.java”檔案
package com.github.carter659.spring05; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ @Controller public class MainController { @Autowired private OrderRepository orderRepository; @GetMapping("/") public String index() { return "index"; } /** * 持久化 * * @param entity * @return */ @PostMapping("/save") public @ResponseBody Map<String, Object> save(@RequestBody Order entity) { Map<String, Object> result = new HashMap<>(); entity = orderRepository.save(entity); result.put("id", entity.id); return result; } /** * 獲取物件 * * @param id * @return */ @PostMapping("/get") public @ResponseBody Object get(String id) { return orderRepository.findOne(id); } /** * 獲取全部 * * @return */ @PostMapping("/findAll") public @ResponseBody Object findAll() { return orderRepository.findAll(); } /** * 刪除 * * @param id * @return */ @PostMapping("/delete") public @ResponseBody Map<String, Object> delete(String id) { Map<String, Object> result = new HashMap<>(); orderRepository.delete(id); result.put("id", id); return result; } }
有人會問,在控制器中直接依賴注入了OrderRepository,並沒有OrderRepository介面的實現類。在沒有寫實現類的情況下不報錯嗎?答案是並不報錯,因為這些事兒都交給了JPA去做。那麼為什麼要用JPA,答案也只有2個字“方便”。我寫這個系列部落格的目的就是為了體現“方便”二字,使用最方便的技術來快速開發專案。
言歸正傳,App.java類保持不變:
![](https://i.iter01.com/images/86153736c3d440f2e7d2df2432d97112d2ef05f0cb7522cf2307c3de9447249a.gif)
package com.github.carter659.spring05; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
完整的專案結構如下圖所示:
執行效果如下圖,我就不做說明了:
二、高階查詢
修改“OrderRepository.java”:
package com.github.carter659.spring05; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ public interface OrderRepository extends JpaRepository<Order, String> { /** * like查詢 * * @param no * @return */ List<Order> findAllByNoLike(String no); /** * between查詢 * * @param startDate * @param endDate * @return */ List<Order> findAllByDateBetween(Date startDate, Date endDate); /** * 小於查詢 * * @param quantity * @return */ List<Order> findAllByQuantityLessThan(int quantity); }
package com.github.carter659.spring05; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * 部落格出處:http://www.cnblogs.com/GoodHelper/ * * @author 劉冬 * */ @Controller public class MainController { @Autowired private OrderRepository orderRepository; /** * 處理日期型別 * * @param binder */ @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } @GetMapping("/") public String index() { return "index"; } /** * 持久化 * * @param entity * @return */ @PostMapping("/save") public @ResponseBody Map<String, Object> save(@RequestBody Order entity) { Map<String, Object> result = new HashMap<>(); entity = orderRepository.save(entity); result.put("id", entity.id); return result; } /** * 獲取物件 * * @param id * @return */ @PostMapping("/get") public @ResponseBody Object get(String id) { return orderRepository.findOne(id); } /** * 獲取全部 * * @return */ @PostMapping("/findAll") public @ResponseBody Object findAll() { return orderRepository.findAll(); } /** * 刪除 * * @param id * @return */ @PostMapping("/delete") public @ResponseBody Map<String, Object> delete(String id) { Map<String, Object> result = new HashMap<>(); orderRepository.delete(id); result.put("id", id); return result; } /** * like查詢 * * @return */ @PostMapping("/findAllByNoLike") public @ResponseBody Object findAllByNoLike(@RequestParam String no) { return orderRepository.findAllByNoLike("%" + no + "%"); } /** * between查詢 * * @return */ @PostMapping("/findAllByDateBetween") public @ResponseBody Object findAllByDateBetween(@RequestParam Date startDate, @RequestParam Date endDate) { return orderRepository.findAllByDateBetween(startDate, endDate); } /** * 小於查詢 * * @return */ @PostMapping("/findAllByQuantityLessThan") public @ResponseBody Object findAllByQuantityLessThan(int quantity) { return orderRepository.findAllByQuantityLessThan(quantity); } }
![](https://i.iter01.com/images/86153736c3d440f2e7d2df2432d97112d2ef05f0cb7522cf2307c3de9447249a.gif)
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>玩轉spring boot——結合JPA</title> <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script> <script type="text/javascript"> /*<![CDATA[*/ var app = angular.module('app', []); app .controller( 'MainController', function($rootScope, $scope, $http) { $scope.data = {}; $scope.rows = []; //新增 $scope.add = function() { $scope.data = { no : 'No.1234567890', quantity : 100, 'date' : '2016-12-30' }; } //編輯 $scope.edit = function(id) { for ( var i in $scope.rows) { var row = $scope.rows[i]; if (id == row.id) { $scope.data = row; return; } } } //移除 $scope.remove = function(id) { for ( var i in $scope.rows) { var row = $scope.rows[i]; if (id == row.id) { $scope.rows.splice(i, 1); return; } } } //儲存 $scope.save = function() { $http({ url : '/save', method : 'POST', data : $scope.data }).success(function(r) { //儲存成功後更新資料 $scope.get(r.id); }); } //刪除 $scope.del = function(id) { $http({ url : '/delete?id=' + id, method : 'POST', }).success(function(r) { //刪除成功後移除資料 $scope.remove(r.id); }); } //獲取資料 $scope.get = function(id) { $http({ url : '/get?id=' + id, method : 'POST', }).success(function(data) { for ( var i in $scope.rows) { var row = $scope.rows[i]; if (data.id == row.id) { row.no = data.no; row.date = data.date; row.quantity = data.quantity; return; } } $scope.rows.push(data); }); } //初始化載入資料 $http({ url : '/findAll', method : 'POST' }).success(function(rows) { for ( var i in rows) { var row = rows[i]; $scope.rows.push(row); } }); $scope.findAllByNoLike = function() { $http( { url : '/findAllByNoLike', method : 'POST', headers : { 'Content-Type' : 'application/x-www-form-urlencoded' }, data : 'no=' + $scope.no }).success(function(rows) { $scope.rows = rows; }); }; $scope.findAllByDateBetween = function() { $http( { url : '/findAllByDateBetween', method : 'POST', headers : { 'Content-Type' : 'application/x-www-form-urlencoded' }, data : 'startDate=' + $scope.startDate + '&endDate=' + $scope.endDate }).success(function(rows) { $scope.rows = rows; }); }; $scope.findAllByQuantityLessThan = function() { $http( { url : '/findAllByQuantityLessThan', method : 'POST', headers : { 'Content-Type' : 'application/x-www-form-urlencoded' }, data : 'quantity=' + $scope.quantity }).success(function(rows) { $scope.rows = rows; }); }; }); /*]]>*/ </script> </head> <body ng-app="app" ng-controller="MainController"> <h1>玩轉spring boot——結合JPA</h1> <h4> <a href="http://www.cnblogs.com/GoodHelper/">from 劉冬的部落格</a> </h4> <input type="button" value="新增" ng-click="add()" /> <input type="button" value="儲存" ng-click="save()" /> <br /> <br /> <h3>訂單資訊:</h3> <input type="hidden" ng-model="data.id" /> <table cellspacing="1" style="background-color: #a0c6e5"> <tr> <td>編號:</td> <td><input ng-model="data.no" /></td> <td>日期:</td> <td><input ng-model="data.date" /></td> <td>數量:</td> <td><input ng-model="data.quantity" /></td> </tr> </table> <br /> <h3>查詢條件:</h3> <table cellspacing="1" style="background-color: #a0c6e5"> <tr> <td>編號:</td> <td><input ng-model="no" /></td> <td><input type="button" ng-click="findAllByNoLike()" value="like查詢" /></td> </tr> <tr> <td>日期:</td> <td>從<input ng-model="startDate" />至<input ng-model="endDate" /></td> <td><input type="button" ng-click="findAllByDateBetween()" value="between查詢" /></td> </tr> <tr> <td>數量:</td> <td><input ng-model="quantity" /></td> <td><input type="button" ng-click="findAllByQuantityLessThan()" value="小於查詢" /></td> </tr> </table> <br /> <h3>訂單列表:</h3> <table cellspacing="1" style="background-color: #a0c6e5"> <tr style="text-align: center; COLOR: #0076C8; BACKGROUND-COLOR: #F4FAFF; font-weight: bold"> <td>操作</td> <td>編號</td> <td>日期</td> <td>數量</td> </tr> <tr ng-repeat="row in rows" bgcolor='#F4FAFF'> <td><input ng-click="edit(row.id)" value="編輯" type="button" /><input ng-click="del(row.id)" value="刪除" type="button" /></td> <td>{{row.no}}</td> <td>{{row.date}}</td> <td>{{row.quantity}}</td> </tr> </table> <br /> <a href="http://www.cnblogs.com/GoodHelper/">點選訪問原版部落格</a> </body> </html>
執行效果:
like查詢:
日期區間查詢:
小於查詢:
總結
JPA的知識點很多,只用一篇部落格是介紹不完的,可能一本書都不一定講完。等以後有機會希望我再寫一個關於JPA的系列。也可以在本系列後面的實踐篇中寫一些與spring boot更多結合的內容。
也可以在文件中查詢到JPA的屬性表示式和JPQL表示式的API:
http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions
http://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html
http://www.objectdb.com/api/java/jpa/queries
程式碼:https://github.com/carter659/spring-boot-05.git
如果你覺得我的部落格對你有幫助,可以給我點兒打賞,左側微信,右側支付寶。
有可能就是你的一點打賞會讓我的部落格寫的更好:)