Spring Boot 菜鸟教程 2 Data JPA

Spring Data JPA

用来简化创建 JPA 数据访问层和跨存储的持久层功能。

官网文档连接

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

Spring Data JPA提供的接口

  • Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别
  • CrudRepository :是Repository的子接口,提供CRUD的功能
  • PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能
  • JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等
  • JpaSpecificationExecutor:用来做负责查询的接口
  • Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可


    Spring Boot 菜鸟教程 2 Data JPA_第1张图片
    这里写图片描述

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)

项目图片

Spring Boot 菜鸟教程 2 Data JPA_第2张图片
项目图片

pom.xml

-只需要在pom.xml引入需要的数据库配置,就会自动访问此数据库,如果需要配置其他数据库,可以在application.properties进行添加
-默认使用org.apache.tomcat.jdbc.pool.DataSource创建连接池


    4.0.0

    com.jege.spring.boot
    spring-boot-data-jpa
    0.0.1-SNAPSHOT
    jar

    spring-boot-data-jpa
    http://maven.apache.org

    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.1.RELEASE
        
    

    
        UTF-8
        1.8
    

    

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

        
        
            com.h2database
            h2
            runtime
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

    

    
        spring-boot-data-jpa
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    ${java.version}
                    ${java.version}
                
            
        
    


模型对象User

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 [email protected]
 * @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;
  }
 }

持久层UserRepository

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 [email protected]
 * @description:持久层接口,由spring自动生成其实现
 */
public interface UserRepository extends JpaRepository {

  List findByNameLike(String name);

}

启动类Application

package com.jege.spring.boot;

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

/**
 * @author JE哥
 * @email [email protected]
 * @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

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 [email protected]
 * @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-boot

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
**您的支持将鼓励我继续创作!谢谢! **

微信打赏
微信打赏

支付宝打赏
支付宝打赏

你可能感兴趣的:(Spring Boot 菜鸟教程 2 Data JPA)