玩轉spring boot——結合JPA入門

 

參考官方例子:https://spring.io/guides/gs/accessing-data-jpa/javascript

接着上篇內容css

 

1、小試牛刀html


 

建立maven項目後,修改pom.xml文件java

<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>
pom.xml

多引入了JPA的依賴:mysql

<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保持上篇不變:git

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
application.properties

 

<!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>
index.html

 

修改上篇的「Order.java」類:github

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」文件web

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<>接口,此接口附帶經常使用的增刪改查到方法。spring

 

修改上篇的控制器「MainController.java」文件sql

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類保持不變:

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);
    }
}
App.java

 

完整的項目結構以下圖所示:

運行效果以下圖,我就不作說明了:

2、高級查詢


 

 修改「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);
    }
}
<!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>
index.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

 

若是你以爲個人博客對你有幫助,能夠給我點兒打賞,左側微信,右側支付寶。

有可能就是你的一點打賞會讓個人博客寫的更好:)

 

玩轉spring boot系列目錄

相關文章
相關標籤/搜索