Spring Data Jpa multi-criteria query and pagination

        Today, the project will need multiple associated conditions of inquiry, to implement a jpa query native is more complicated, but jpa provided entityManger this class can implement sql query custom so that we can write native sql order to achieve multi Conditions query the implementation is relatively simple

1. Fill the entity class entityManger

 @Autowired
 private EntityManager entityManager;

2. Call entityManger.createNativeQuery () method implementation inquiry, in the course of realization of the need to use the paging org.springframework.data.domain.PageImpl; this class he is to achieve the object of the class page, when calling will find our incoming pageable argument does not work, it is because the object can not be pageable paging operation to check out the collection we have so needs to achieve his method of paging we manually.

Code Example:

public Page<StutsDk> execQuerySqlPage(Pageable pageable, String sql) {

        Query query = this.entityManager.createNativeQuery(sql,StutsDk.class);

        List<StutsDk> stutsDks=query.getResultList();
        if (pageable.getOffset() > stutsDks.size()) {
            long total = 0L;
            PageImpl<StutsDk> page = new PageImpl<>(stutsDks,pageable,total);
            return page;
        }
        if (pageable.getOffset() <= stutsDks.size() && pageable.getOffset() + pageable.getPageSize() > stutsDks.size()) {
            List<StutsDk> bizPojos = stutsDks.subList(pageable.getOffset(), stutsDks.size());
            PageImpl<StutsDk> page = new PageImpl<>(bizPojos, pageable, stutsDks.size());
            return page;
        }
        List<StutsDk> newStutsDks = stutsDks.subList(pageable.getOffset(), pageable.getOffset() + pageable.getPageSize());
        PageImpl<StutsDk> page = new PageImpl<StutsDk>(newStutsDks, pageable, stutsDks.size());
        return page;
    }

          Call createNativeQuery () if you do not write the entity class map to be returned will be the list <Object> collection when we can call query method query object query.unwrap () method to convert it to list <Map <, >> collection.

The method of the above two fast codes in the called a pageable

pageable.getOffset()

pageable.getPageSize()

Respectively, the number of acquired data and the offset data to be returned and rows

 

Released six original articles · won praise 7 · views 1102

Guess you like

Origin blog.csdn.net/weixin_43814408/article/details/88047423