亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

Spring Data JPA 教程系列

JayChen / 1090人閱讀

摘要:測(cè)試程序首先看到頂層服務(wù)使用格式進(jìn)行輸出。的列舉包括以下值默認(rèn),公開所有公開和注解的,除非設(shè)置為暴露所有修飾的創(chuàng)建配置類測(cè)試分頁(yè)和排序分頁(yè)是一個(gè)由定義的接口,它擁有一個(gè)實(shí)現(xiàn)。排序提供一個(gè)對(duì)象提供排序機(jī)制。

使用 JPA 訪問數(shù)據(jù) 創(chuàng)建項(xiàng)目

打開IDEA -> Create New Project

創(chuàng)建目錄

創(chuàng)建實(shí)體
package com.example.demo.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Customer {

    @Id
    @GeneratedValue
    private Long id;
    private String firstName;
    private String lastName;

    protected Customer() {
    }

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", firstName=" + firstName +
                ", lastName=" + lastName +
                "}";
    }
}
創(chuàng)建 repository

創(chuàng)建與實(shí)體對(duì)應(yīng)的Repository

package com.example.demo.repository;

import com.example.demo.entity.Customer;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface CustomerRepository extends CrudRepository {

    List findByLastName(String lastName);

}

通過繼承CrudRepository繼承幾種增刪改查方法,也可以通過方法名支定義其他查詢方法。

添加啟動(dòng)加載類 CommandLineRunner 測(cè)試
package com.example.demo;

import com.example.demo.entity.Customer;
import com.example.demo.repository.CustomerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SpringDataJpaDemoApplication {

    public static final Logger log = LoggerFactory.getLogger(SpringDataJpaDemoApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(SpringDataJpaDemoApplication.class, args);
    }

    @Bean
    public CommandLineRunner demo(CustomerRepository repository) {
        return (args -> {

            repository.save(new Customer("Jack", "Bauer"));
            repository.save(new Customer("Chloe", "Brian"));
            repository.save(new Customer("Kim", "Bauer"));
            repository.save(new Customer("David", "Palmer"));
            repository.save(new Customer("Michelle", "Dessler"));

            log.info("Customer found with save() finish");

            log.info("Customer found with findAll()");
            log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            for (Customer customer : repository.findAll()) {
                log.info(customer.toString());
            }
            log.info("");

            repository.findById(1L).ifPresent(customer -> {
                log.info("Customer found with findById()");
                log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                log.info(customer.toString());
                log.info("");
            });

            log.info("Customer found with findByLastName("findByLastName")");
            log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            repository.findByLastName("Bauer").forEach(bauer -> {
                log.info(bauer.toString());
            });
            log.info("");

        });
    }


}

運(yùn)行程序,通過 log 查看效果

使用 REST 訪問 JPA 數(shù)據(jù)

pom.xml 添加依賴



    
    
        
        
            org.springframework.boot
            spring-boot-starter-data-rest
        
        
    



創(chuàng)建實(shí)體
package com.example.demo.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    private String firstName;
    private String lastName;
    
    
    public String getFirstName() {
        return firstName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    public String getLastName() {
        return lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}
創(chuàng)建 repository
package com.example.demo.repository;

import com.example.demo.entity.Person;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

@RepositoryRestResource
public interface PersonRepository extends PagingAndSortingRepository {
    
    List findPersonByLastName(@Param("name") String name);
    
}

此repository是一個(gè)接口,允許您執(zhí)行涉及Person對(duì)象的各種操作。它通過繼承Spring Data Commons中定義的PagingAndSortingRepository接口來獲取這些操作

在運(yùn)行時(shí),Spring Data REST將自動(dòng)創(chuàng)建此接口的實(shí)現(xiàn)。然后它將使用@RepositoryRestResource注解指導(dǎo)Spring MVC創(chuàng)建RESTful端點(diǎn)/persons。

測(cè)試程序

首先看到頂層服務(wù)

curl http://localhost:8080/
{
  "_links" : {
    "customers" : {
      "href" : "http://localhost:8080/customers"
    },
    "persons" : {
      "href" : "http://localhost:8080/persons{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile"
    }
  }
}
Spring Data REST使用HAL格式進(jìn)行JSON輸出。它非常靈活,可以方便地提供與所服務(wù)數(shù)據(jù)相鄰的鏈接。
curl http://localhost:8080/persons
{
  "_embedded" : {
    "persons" : [ ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/persons"
    },
    "search" : {
      "href" : "http://localhost:8080/persons/search"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 0,
    "totalPages" : 0,
    "number" : 0
  }
}

可以看到customers的也跟著顯示出來了,我們可以通過注釋隱藏,當(dāng)然也可以全局隱藏:

設(shè)置存儲(chǔ)庫(kù)檢測(cè)策略

Spring Data REST使用RepositoryDetectionStrategy來確定是否將存儲(chǔ)庫(kù)導(dǎo)出為REST資源。的RepositoryDiscoveryStrategies列舉包括以下值:

Name Description
DEFAULT 默認(rèn),ANNOTATION + VISIBILITY
ALL 公開所有Repository
ANNOTATION 公開@RepositoryRestResource和@RestResource注解的Repository,除非exported設(shè)置為false
VISIBILITY 暴露所有public修飾的Repository

創(chuàng)建配置類

package com.example.demo.config;

import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.core.mapping.RepositoryDetectionStrategy;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.stereotype.Component;

@Component
public class RestConfigurer implements RepositoryRestConfigurer {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.setRepositoryDetectionStrategy(RepositoryDetectionStrategy.RepositoryDetectionStrategies.ANNOTATED);
    }

}

測(cè)試

curl http://localhost:8080/
{
  "_links" : {
    "persons" : {
      "href" : "http://localhost:8080/persons{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile"
    }
  }
}
分頁(yè)和排序 分頁(yè)

Pageable 是一個(gè)由 Spring 定義的接口,它擁有一個(gè)實(shí)現(xiàn) PageRequest。讓我們看看如何創(chuàng)建一個(gè) PageRequest。

Pageable pageable = PageRequest.of(0, 10);
Page page = repository.findAll(pageable);

// 也可以簡(jiǎn)單一點(diǎn)

Page page = repository.findAll(PageRequest.of(0, 10));

表示請(qǐng)求第一頁(yè)10個(gè)數(shù)據(jù)。

如果我們要訪問下一頁(yè),我們可以每次增加頁(yè)碼。

PageRequest.of(1, 10);
PageRequest.of(2, 10);
PageRequest.of(3, 10);
...
排序

Spring Data JPA 提供一個(gè)Sort對(duì)象提供排序機(jī)制。讓我們看一下排序的方式。

repository.findAll(Sort.by("fistName"));

repository.findAll(Sort.by("fistName").ascending().and(Sort.by("lastName").descending());
同時(shí)排序和分頁(yè)
Pageable pageable = PageRequest.of(0, 20, Sort.by("firstName"));

Pageable pageable = PageRequest.of(0, 20, Sort.by("fistName").ascending().and(Sort.by("lastName").descending());
按示例對(duì)象查詢

QueryByExampleExecutor

構(gòu)建復(fù)雜查詢

SpringData JPA 為了實(shí)現(xiàn) "Domain Driven Design" 中的規(guī)范概念,提供了一些列的 Specification 接口,其中最常用的便是 :JpaSpecificationExecutor。

使用 SpringData JPA 構(gòu)建復(fù)雜查詢(join操作,聚集操作等等)都是依賴于 JpaSpecificationExecutor 構(gòu)建的 Specification 。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/73506.html

相關(guān)文章

  • Spring Boot 教程(二):使用Spring Boot JPA完成數(shù)據(jù)層訪問

    摘要:教程簡(jiǎn)介本項(xiàng)目?jī)?nèi)容為教程樣例。目的是通過學(xué)習(xí)本系列教程,讀者可以從到掌握的知識(shí),并且可以運(yùn)用到項(xiàng)目中。本章將進(jìn)一步講解,結(jié)合完成數(shù)據(jù)層訪問。創(chuàng)建控制器在下面創(chuàng)建控制器用于測(cè)試訪問程序運(yùn)行和調(diào)試在類中,啟動(dòng)程序。 教程簡(jiǎn)介 本項(xiàng)目?jī)?nèi)容為Spring Boot教程樣例。目的是通過學(xué)習(xí)本系列教程,讀者可以從0到1掌握spring boot的知識(shí),并且可以運(yùn)用到項(xiàng)目中。如您覺得該項(xiàng)目對(duì)您有用,...

    DevWiki 評(píng)論0 收藏0
  • 一起來學(xué)SpringBoot | 第六篇:整合SpringDataJpa

    摘要:忽略該字段的映射省略創(chuàng)建數(shù)據(jù)訪問層接口,需要繼承,第一個(gè)泛型參數(shù)是實(shí)體對(duì)象的名稱,第二個(gè)是主鍵類型。 SpringBoot 是為了簡(jiǎn)化 Spring 應(yīng)用的創(chuàng)建、運(yùn)行、調(diào)試、部署等一系列問題而誕生的產(chǎn)物,自動(dòng)裝配的特性讓我們可以更好的關(guān)注業(yè)務(wù)本身而不是外部的XML配置,我們只需遵循規(guī)范,引入相關(guān)的依賴就可以輕易的搭建出一個(gè) WEB 工程 上一篇介紹了Spring JdbcTempl...

    Dionysus_go 評(píng)論0 收藏0
  • Spring Boot 的簡(jiǎn)單教程(四)數(shù)據(jù)庫(kù)連接之Spring Data JPA的使用

    摘要:以前都是用進(jìn)行數(shù)據(jù)庫(kù)的開發(fā),最近學(xué)習(xí)之后發(fā)現(xiàn)顯得更友好,所以我們就一起來了解一下的原理吧。簡(jiǎn)單介紹持久性是的一個(gè)規(guī)范。它用于在對(duì)象和關(guān)系數(shù)據(jù)庫(kù)之間保存數(shù)據(jù)。充當(dāng)面向?qū)ο蟮念I(lǐng)域模型和關(guān)系數(shù)據(jù)庫(kù)系統(tǒng)之間的橋梁。是標(biāo)識(shí)出主鍵是指定主鍵的自增方式。 以前都是用Mybatis進(jìn)行數(shù)據(jù)庫(kù)的開發(fā),最近學(xué)習(xí)Spring Boot之后發(fā)現(xiàn)JPA顯得更友好,所以我們就一起來了解一下JPA的原理吧。 Spr...

    yuxue 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

閱讀需要支付1元查看
<