Spring Data Jpa basis -01

SpringData:

Spring Data is used to simplify database access, and support for open-source framework for cloud services. Its main goal is to make access to the data becomes fast and convenient, and map-reduce framework to support cloud computing and data services. Spring Data contains multiple components:

  1. Commons - provide the basis for a shared framework for each sub-project use, support for cross-database persistence
  2. JPA - function simplifies the creation of JPA persistence layer and data access layer across storage
  3. Hadoop - Hadoop jobs Spring-based configuration and a POJO programming model MapReduce jobs
  4. Key-Value - integrated Redis and Riak, provide a simple packaging at a plurality of common scenes
  5. Document - integrated document databases: CouchDB and MongoDB and provides basic configuration mapping and database support
  6. Graph - provides a powerful integrated Neo4j POJO-based programming model
  7. Graph Roo AddOn - Roo support for Neo4j
  8. JDBC Extensions - supports Oracle RAD, Advanced Queuing, and advanced data types
  9. Mapping - based on providing object mapping framework Grails to support different database
  10. Examples - sample programs, documents and databases
  11. Guidance - Advanced Document

SpringDataJPA:

Provided by the Spring JPA a framework for simplifying the development.

Function: the case can be greatly simplified JPA wording, can almost not write specific method (i.e. interface) to achieve access and manipulate data. In addition to the CRUD, further comprising a number of frequently used functions such as paging, sorting and the like.

What Spring Data JPA have?

The main take a look at the interface provided by Spring Data JPA, also Spring Data JPA's core concepts:

  1. Repository: top level interface is an empty interface, the purpose of all Repository uniform type, and when the scan assembly allows automatic identification.
  2. CrudRepository: Repository is a sub-interface, providing CRUD functionality
  3. PagingAndSortingRepository: CrudRepository is sub-interface, add the paging and sorting functions
  4. JpaRepository: PagingAndSortingRepository is sub-interface, and adds some useful features, such as: batch operation.
  5. JpaSpecificationExecutor: used to make the query interface is responsible for
  6. Specification: a query specification is provided by Spring Data JPA, to do complex queries, just around this specification can be set query conditions

 

JpaRepository query:

In the direct query methods defined in the interface, if it is compliant, you can not write implementation currently supports keyword worded as follows:

JpaRepository method defined keywords
KeyWord (keyword) The Sample (method name Example) JPQL snippet (JPQL corresponding statement)
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% _ the tail for binding%, EG: startStr% )
EndingWith findByFirstnameEndingWith ? where x.firstname like 1 (parameter bound with prepended% _ parameter binding pre-%, EG: % endStr )
Containing findByFirstnameContaining

? where x.firstname like 1 (parameter bound wrapped in% _ % contain parameters, 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)   使用一个特定的数据库表格保存主键。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/J1014329058/article/details/85113029