日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Boot 之Spring data JPA简介

發(fā)布時間:2024/2/28 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Boot 之Spring data JPA简介 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 添加依賴
    • 添加entity bean
    • 創(chuàng)建 Dao
    • Spring Data Configuration
    • 測試

Spring Boot 之Spring data JPA簡介

JPA的全稱是Java Persistence API (JPA),他是一個存儲API的標(biāo)準(zhǔn),而Spring data JPA就是對JPA的一種實現(xiàn),可以讓我們方便的對數(shù)據(jù)進行存取。按照約定好的方法命名規(guī)則寫dao層接口,從而在不實現(xiàn)接口的情況下,實現(xiàn)對數(shù)據(jù)庫的訪問和操作。同時提供了很多除了CRUD之外的功能,如分頁、排序、復(fù)雜查詢等等。

Spring data JPA可以看做是對Hibernate的二次封裝。本文將會以一個具體的例子來講解,怎么在Spring Boot中使用Spring data JPA。

添加依賴

我們要添加如下的Spring data JPA依賴,為了方便測試,我們添加一個h2的內(nèi)存數(shù)據(jù)庫:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency>

添加entity bean

我們來創(chuàng)建一個entity bean:

@Entity @Data public class Book {@Id@GeneratedValue(strategy = GenerationType.AUTO)private long id;@Column(nullable = false, unique = true)private String title;@Column(nullable = false)private String author; }

創(chuàng)建 Dao

public interface BookRepository extends JpaRepository<Book, Long> {List<Book> findByTitle(String title);@Query("SELECT b FROM Book b WHERE LOWER(b.title) = LOWER(:title)")Book retrieveByTitle(@Param("title") String title); }

所有的Dao都需要繼承Repository接口,Repository是一個空的接口:

@Indexed public interface Repository<T, ID> {}

如果要使用默認的通用的一些實現(xiàn),則可以繼承CrudRepository, PagingAndSortingRepository和JpaRepository。

上面的例子中我們繼承了JpaRepository。

上面的例子中我們創(chuàng)建了一個按Title查找的方法:

List<Book> findByTitle(String title);

這個方法我們是不需要自己去實現(xiàn)的,Spring Data JPA會幫我們?nèi)崿F(xiàn)。我們可以使用find…By, read…By, query…By, count…By,和 get…By的格式定義查詢語句,By后面接的就是Entity的屬性。除了And,我們還可以使用Or來拼接方法,下面我們再舉個例子:

interface PersonRepository extends Repository<Person, Long> {List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);// Enables the distinct flag for the queryList<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);// Enabling ignoring case for an individual propertyList<Person> findByLastnameIgnoreCase(String lastname);// Enabling ignoring case for all suitable propertiesList<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);// Enabling static ORDER BY for a queryList<Person> findByLastnameOrderByFirstnameAsc(String lastname);List<Person> findByLastnameOrderByFirstnameDesc(String lastname); }

當(dāng)然,處理方法拼接外,我們還可以自定義sql查詢語句:

@Query("SELECT b FROM Book b WHERE LOWER(b.title) = LOWER(:title)")Book retrieveByTitle(@Param("title") String title);

自定義查詢語句給Spring data JPA提供了更大的想象空間。

Spring Data Configuration

要使用Spring Data JPA, 我們還需要在配置文件中指定要掃描的目錄,使用@EnableJpaRepositories注解來實現(xiàn):

@Configuration @EnableJpaRepositories(basePackages = "com.flydean.repository") public class PersistenceConfig { }

我們還需要在配置文件中指定數(shù)據(jù)源的屬性:

spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password=sa

測試

有了上面的一切,我們就可以測試我們的數(shù)據(jù)源了:

@Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = {JpaApp.class}) public class BookRepositoryTest {@Autowiredprivate BookRepository bookRepository;@Test@Transactional(readOnly=false)public void testBookRepository(){Book book = new Book();book.setTitle(randomAlphabetic(10));book.setAuthor(randomAlphabetic(15));bookRepository.save(book);bookRepository.findByTitle(book.getTitle()).forEach(e -> log.info(e.toString()));log.info(bookRepository.retrieveByTitle(book.getTitle()).toString());} }

本文的例子可以參考:https://github.com/ddean2009/learn-springboot2/tree/master/springboot-jpa

更多精彩內(nèi)容且看:

  • 區(qū)塊鏈從入門到放棄系列教程-涵蓋密碼學(xué),超級賬本,以太坊,Libra,比特幣等持續(xù)更新
  • Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續(xù)更新
  • Spring 5.X系列教程:滿足你對Spring5的一切想象-持續(xù)更新
  • java程序員從小工到專家成神之路(2020版)-持續(xù)更新中,附詳細文章教程

更多教程請參考 flydean的博客

總結(jié)

以上是生活随笔為你收集整理的Spring Boot 之Spring data JPA简介的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。