Spring Boot 系列教程2-Data JPA

Spring Data JPA

用來簡化建立 JPA 數據訪問層和跨存儲的持久層功能。html

官網文檔鏈接

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/java

Spring Data JPA提供的接口

  • Repository:最頂層的接口,是一個空的接口,目的是爲了統一全部Repository的類型,且能讓組件掃描的時候自動識別
  • CrudRepository :是Repository的子接口,提供CRUD的功能
  • PagingAndSortingRepository:是CrudRepository的子接口,添加分頁和排序的功能
  • JpaRepository:是PagingAndSortingRepository的子接口,增長了一些實用的功能,好比:批量操做等
  • JpaSpecificationExecutor:用來作負責查詢的接口
  • Specification:是Spring Data JPA提供的一個查詢規範,要作複雜的查詢,只需圍繞這個規範來設置查詢條件便可
    這裏寫圖片描述

項目圖片

這裏寫圖片描述

pom.xml

-只須要在pom.xml引入須要的數據庫配置,就會自動訪問此數據庫,若是須要配置其餘數據庫,能夠在application.properties進行添加
-默認使用org.apache.tomcat.jdbc.pool.DataSource建立鏈接池git

<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.jege.spring.boot</groupId>
    <artifactId>spring-boot-data-jpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-data-jpa</name>
    <url>http://maven.apache.org</url>

    <!-- 公共spring-boot配置,下面依賴jar文件不用在寫版本號 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
        <relativePath />
    </parent>

    <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-data-jpa</artifactId>
        </dependency>

        <!-- h2內存數據庫 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <finalName>spring-boot-data-jpa</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

User.java

package com.jege.spring.boot.data.jpa.entity;

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

/** * @author JE哥 * @email 1272434821@qq.com * @description:jpa模型對象 */
@Entity
@Table(name = "t_user")
public class User {
  @Id
  @GeneratedValue
  private Long id;
  private String name;
  private Integer age;

  public User() {

  }

  public User(String name, Integer age) {
    this.name = name;
    this.age = age;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

}

UserRepository.java

package com.jege.spring.boot.data.jpa.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.jege.spring.boot.data.jpa.entity.User;

/** * @author JE哥 * @email 1272434821@qq.com * @description:持久層接口,由spring自動生成其實現 */
public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByNameLike(String name);

}

Repository接口查詢規則

關鍵字 案例 效果
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

Application.java

package com.jege.spring.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/** * @author JE哥 * @email 1272434821@qq.com * @description:spring boot 啓動類 */

@SpringBootApplication
public class Application {

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

}

application.properties

## JPA Settings
spring.jpa.generate-ddl: true
spring.jpa.show-sql: true
spring.jpa.hibernate.ddl-auto: create
spring.jpa.properties.hibernate.format_sql: false

UserRepositoryTest.java

package com.jege.spring.boot.data.jpa;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.jege.spring.boot.data.jpa.entity.User;
import com.jege.spring.boot.data.jpa.repository.UserRepository;

/** * @author JE哥 * @email 1272434821@qq.com * @description: */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest()
public class UserRepositoryTest {
  @Autowired
  UserRepository userRepository;

  // 打印出class com.sun.proxy.$Proxy66表示spring注入經過jdk動態代理獲取接口的子類
  @Test
  public void proxy() throws Exception {
    System.out.println(userRepository.getClass());
  }

  @Test
  public void save() throws Exception {
    for (int i = 0; i < 10; i++) {
      User user = new User("jege" + i, 25 + i);
      userRepository.save(user);
    }
  }

  @Test
  public void all() throws Exception {
    save();
    assertThat(userRepository.findAll()).hasSize(10);
  }

  @Test
  public void findByName() throws Exception {
    save();
    assertThat(userRepository.findByNameLike("jege%")).hasSize(10);
  }

  @After
  public void destroy() throws Exception {
    userRepository.deleteAll();
  }

}

源碼地址

https://github.com/je-ge/spring-bootgithub

若是以爲個人文章對您有幫助,請予以打賞。您的支持將鼓勵我繼續創做!謝謝!
微信打賞
支付寶打賞spring

相關文章
相關標籤/搜索