SpringData JPA接口简单总结

1 JPA

1.1 整体概念

JPA:Java Persistence API,就是java持久化api,是SUN公司推出的一套基于ORM的规范。

ORM呢:Object-Relational Mapping,对象关系映射,简单来说为了不用JDBC那一套原始方法来操作数据库,ORM框架横空出世(mybatis、hibernate等等)。

Spring Data JPA是Spring Data家族的一部分,可以轻松实现基于JPA的存储库。 此模块处理对基于JPA的数据访问层的增强支持。 它使构建使用数据访问技术的Spring驱动应用程序变得更加容易。

总的来说JPA是ORM规范,Hibernate、TopLink等是JPA规范的具体实现,这样的好处是开发者可以面向JPA规范进行持久层的开发,而底层的实现则是可以切换的。Spring Data Jpa则是在JPA之上添加另一层抽象(Repository层的实现),极大地简化持久层开发及ORM框架切换的成本。

SpringData JPA接口简单总结

1.2 JPA实体生命周期

SpringData JPA接口简单总结
PostLoad
PostPersist
PostRemove
PostUpdate
PrePersist
PreRemove
PreUpdate
import org.springframework.stereotype.Component;
 
import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
 
public class TestEntityListeners {
 
	@PrePersist
	public void PrePersist(Object entity){
		System.out.println("开始保存--"+entity.toString());
	}
  
	@PreUpdate
	public void PreUpdate(Object entity){
		System.out.println("开始更新--"+entity.toString());
	}
 
	@PostPersist
	public void PostPersist(Object entity){
		System.out.println("结束保存--"+entity.toString());
	}
 
	@PostUpdate
	public void PostUpdate(Object entity){
		System.out.println("结束更新--"+entity.toString());
	}
  
}
@Entity
@Table(name = "product")
@EntityListeners(value = {TestEntityListeners.class})
public class Product {
	private int id;
	private String productId;
	private String productName;
    //getter setter toString()
}

2 JpaEntityInformation

JpaEntityInformation entityInformation = JpaEntityInformationSupport.getEntityInformation(clazz, entityManager);

3 Repository

3.1 Repository

SpringData JPA接口简单总结
  • JpaRepositoryImplementation<T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T>

    • SPI interface to be implemented by JpaRepository implementations.
    • SPI是串行外设接口(Serial Peripheral Interface)的缩写
  • RevisionRepository<T, ID, N extends Number & Comparable<N>> extends Repository<T, ID>

    • A repository which can access entities held in a variety of Revisions.

    • private final JpaEntityInformation<T, ?> entityInformation;
      private final EntityManager em;
      private final PersistenceProvider provider;
      
  • public class SimpleJpaRepository<T, ID> implements JpaRepositoryImplementation<T, ID>

    • SpringData JPA接口简单总结
  • 其他子类:

    • SpringData JPA接口简单总结
    • SpringData JPA接口简单总结
  • @NoRepositoryBean

3.2 Optional

  • SpringData JPA接口简单总结
  • SpringData JPA接口简单总结

示例:

    public static void main(String[] args) {
        System.out.println("------- 1.get() 若为null会报错");
//        Optional<String> empty = Optional.empty();
//        System.out.println(empty.get());
        /*
            public T get() {
                if (value == null) {
                    throw new NoSuchElementException("No value present");
                }
                return value;
            }
         */

        System.out.println("------- 2.Optional.of()");
//        Optional<Object> empty = Optional.of(null);
//        System.out.println(empty.get());
        /*
            public static <T> Optional<T> of(T value) {
                return new Optional<>(value);
            }
            private Optional(T value) {
                this.value = Objects.requireNonNull(value);
            }

            public static <T> Optional<T> ofNullable(T value) {
                return value == null ? empty() : of(value);
            }
         */

        System.out.println("------- 3.Optional.ofNullable()");
//        Optional<Object> empty = Optional.ofNullable(null);
//        System.out.println(empty.get());

        System.out.println("------- 4.Optional.isPresent()");
        Optional<Object> empty = Optional.empty();
        System.out.println(empty.isPresent());

        System.out.println("------- 5.Optional.ifPresent()");
        Optional<String> optional = Optional.of("haha");
        optional.ifPresent(str -> System.out.println("参数有值时打印:" + str));

        System.out.println("------- 6.Optional.filter()");
        boolean present = optional.filter(str -> "hehe".equals(str)).isPresent();
        System.out.println(present);

        System.out.println("------- 7.Optional.map()");
        Optional<String> optional2 = optional.map(str -> str.toUpperCase());
        System.out.println(optional2.get());

        System.out.println("------- 8.Optional.flatMap()");
        Optional<String> s = optional.flatMap(str -> Optional.ofNullable(str.toUpperCase()));
        System.out.println(s.get());

        System.out.println("------- 9.Optional.orElse()");
        Object haha = Optional.empty().orElse("haha");
        System.out.println(haha);

        System.out.println("------- 10.Optional.orElseGet()");
        Object o = Optional.empty().orElseGet(() -> Math.random());
        System.out.println(o);

        System.out.println("------- 11.Optional.orElseThrow()");

    }

3.3 Limit Query

List<User> findFirst10ByLastname(String lastname, Sort sort);

List<User> findTop10ByLastname(String lastname, Pageable pageable);

3.4 Null

SpringData JPA接口简单总结

3.5 Asynchronous Query Results

SpringData JPA接口简单总结
上一篇:SpringData JPA入门


下一篇:Springdata JPA、MyBatis选型