Spring Data Jpa基础-01

SpringData:

Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务。 Spring Data 包含多个子项目:

  1. Commons - 提供共享的基础框架,适合各个子项目使用,支持跨数据库持久化
  2. JPA - 简化创建 JPA 数据访问层和跨存储的持久层功能
  3. Hadoop - 基于 Spring 的 Hadoop 作业配置和一个 POJO 编程模型的 MapReduce 作业
  4. Key-Value  - 集成了 Redis 和 Riak ,提供多个常用场景下的简单封装
  5. Document - 集成文档数据库:CouchDB 和 MongoDB 并提供基本的配置映射和资料库支持
  6. Graph - 集成 Neo4j 提供强大的基于 POJO 的编程模型
  7. Graph Roo AddOn - Roo support for Neo4j
  8. JDBC Extensions - 支持 Oracle RAD、高级队列和高级数据类型
  9. Mapping - 基于 Grails 的提供对象映射框架,支持不同的数据库
  10. Examples - 示例程序、文档和图数据库
  11. Guidance - 高级文档

SpringDataJPA:

由Spring提供的一个用于简化JPA开发的框架。

功能:可以极大的简化JPA的写法,可以在几乎不用写具体实现方法(即接口)的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能。

Spring Data JPA有什么?

主要来看看Spring Data JPA提供的接口,也是Spring Data JPA的核心概念:

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

JpaRepository的查询:

直接在接口中定义查询方法,如果是符合规范的,可以不用写实现,目前支持的关键字写法如下:

JpaRepository方法定义关键字
KeyWord(关键词) Sample(方法名实例) JPQL snippet(对应的JPQL语句)
And findByLastNameAndFirstName where x.lastname=?1  and x.firstname=?2

Or

findByLastnameOrFirstname where x.lastname=?1  or x.firstname=?2
Between findByStartDateBetween where x.startDate between ?1  and ?2
LessThan findByAgeLessThan where x.age < ?1
LessThanEqual findByAgeLessThenEqual where x.age <= ?1
GreaterThan findByAgeGreeterThan where x.age > ?1
GreaterThenEqual findByAgeGreeterThanEqual 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 findByAgeIsNotNull / findByAgeNotNull 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 ? (parameter bound with appended % _参数尾部绑定%,eg:startStr%)
EndingWith findByFirstnameEndingWith where x.firstname like ?1 (parameter bound with prepended %_参数绑定前置%,eg:%endStr)
Containing findByFirstnameContaining

where x.firstname like ?1 (parameter bound wrapped in %_参数使用%包含,eg:%paraStr%)

OrderBy findByAgeOrderByLastnameDesc/Asc where x.age= ?1 order by x.lastname desc/asc
Not findbyLastnameNot where x.lastname <> ?1
In findByAgeIn(Collection ages) where x.age in ( age1,age2,age2... )
NotIn findByAgeNotIn(Collection ages) where x.age not in ( age1,age2,age2... )
True findByActiveTrue() where x.active = true
False findByActiveFalse() where x.active = false
IgnoreCase findByFirstnameIgnoreCase() where UPPER( x.firstname ) = UPPER( ?1 )
findFirstByOrderBy*Asc/Desc findFirstByOrderByLastnameAsc/Desc() 按照姓氏 正序/倒叙 排列,查询排在第一行的记录
Page<User> queryFirst10ByLastname(String lastname, Pageable pageable) 根据姓氏按照分页对象查询,获取排在前10行的记录
List<User>    findFirst10ByLastname(String lastname,  Sort sort) 根据姓氏按照排序方式,获取排在前10行的记录
List<User>  findTop10ByLastname (String lastname, Pageable pageable); 根据姓氏按照分页对象查询,获取排在前10行的记录

JPA分页查询:

//Dao接口定义分页查询方法:
Page<User> findByUserName(String userName,Pageable pageable);

//调用测试Dao定义的分页查询方法:
public void testFindUserList(){
    int page = 1;   //当前页码
    int size = 10;  //每页大小
    Sort sort = new Sort(Direction.DESC,"id");  //根据id降序
    Pageable pageable = new PageRequest(page,size,sort);
    //Pageable pageable = new PageRequest(1,10,Direction.DESC,"id");
    Page<User> page = repository.findByUserName("testName",pageable);
    
    System.out.println(page.getTotalElements()); //总记录数
    System.out.println(page.getTotalPages()); //总页数
    //打印查询数据
    for (User user: page.getContent()) {
        System.out.println(user.toString());
    }
}

JPA自定义查询:

@Modifying  //涉及记录删除和修改
@Query("update User u set u.userName = ? where c.id = ?") //sql语句
int modifyByIdAndUserId(String userName, Long id);


@Transactional  //涉及事务
@Modifying  //涉及记录的删除和修改
@Query("delete from User where id = ?")
void deleteByUserId(Long id);


@Transactional(timeout = 10) //设置超时查询10s,默认30s()
@Query("select u from User u where u.emailAddress = ?")
User findByEmailAddress(String emailAddress);

JPA主键生成方式:

1.用hibernate的uuid主键生成器,下面两种实例均可:

  •   @GeneratedValue(generator="system-uuid")             JPA通用策略生成器
  •   @GenericGenerator(name="system-uuid",strategy="uuid")         自定义主键生成策略(strategy:生成策略)

2.JPA提供的四种标准主键生成器策略:

  • @GeneratedValue(generator=GenerationType.AUTO)       主键由程序控制。
  • @GeneratedValue(generator=GenerationType.IDENTITY)  主键由数据库自动生成(自增型号)。
  • @GeneratedValue(generator=GenerationType.SEQUENCE)  根据底层数据库的序列号生成,前提是数据库支持序列(例如oracle)。
  • @GeneratedValue(generator=GenerationType.TABLE)   使用一个特定的数据库表格保存主键。

猜你喜欢

转载自blog.csdn.net/J1014329058/article/details/85113029
今日推荐