Spring JPA 分页查询

1. 之前一直用别人的框架,进行分页。这次项目需要Spring JPA分页 ,动手写了一下。

其实 Spring JPA 已经有封装好的分页方法,但是,那些只适合特定的查询条件, 不适合动态条件查询。

方法1:

注意表名啥的都用数据库中的名称, 适用于特定数据库的查询
public interface UserRepository extends JpaRepository<User, Long> {
 
	@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1"
, countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1"
, nativeQuery = true)
	Page<User> findByLastname(String lastname, Pageable pageable);
 
	@Query(value = "SELECT u  FROM Users u WHERE u.username like %:username%")
	List<User> findByName(@Param("username") String username);
}
Query注解,hql语句
适用于查询指定条件的数据
@Query(value = "select b.roomUid from RoomBoard b where b.userId=:userId and b.lastBoard=true order by  b.createTime desc")
Page<String> findRoomUidsByUserIdPageable(@Param("userId") long userId, Pageable pageable);

方法2: 动态条件查询

单表查询;

/***
     * 查询   分页数据
     *
     **/
	public Page<DeviceInfoEntity> page(SearchDTO searchDto){
		Specification<DeviceInfoEntity> spec = new Specification<DeviceInfoEntity>() { // 查询条件构造
			@Override
			public Predicate toPredicate(Root<DeviceInfoEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>(); 
				Path<String> authStatus = root.get("authStatus"); //授权状态
				Path<String> devName = root.get("devName");
				Path<String> devMode = root.get("devMode");
				Predicate preP = null;
				if(searchDto.getAuthStatus() != null && searchDto.getAuthStatus() > 0){
					Predicate p1 = cb.equal(authStatus, searchDto.getAuthStatus());
					 preP = cb.and(p1);
				}
				
				if(StringUtils.isNotBlank(searchDto.getDevKeyword())){ //模糊查询
					Predicate p2 = cb.like(devName, "%" + searchDto.getDevKeyword() + "%");
					Predicate p3 = cb.like(devMode, "%" + searchDto.getDevKeyword() + "%");
					if(preP!=null){
                        preP = cb.and(preP,cb.or(p2,p3));
                    }else{
                    	preP = cb.or(p2,p3);
                    }
				} 
				predicate.add(preP);
	            Predicate[] pre = new Predicate[predicate.size()];
	            query.where(predicate.toArray(pre));
	            return query.getRestriction();
			} 
		 };   
		 Page<DeviceInfoEntity> page = deviceInfoDao.findAll(spec, searchDto.toPageable());
		 return page;
	}

 多表联合查询:

先创建一个对象, 和查询出的结果对应:

@Data //lombok
@Entity //这个注解必备
public class TempInfoPageEntity  implements Serializable {

	@Transient   
	private static final long serialVersionUID = 1L;
	
	/**
     * 注释:ID
     */
	@Id //这个注解必备 接收分页查询 ,必须有个id
    private Long id;

    private String devId;
	
    private String devName;
	
    private String devMode;
	
    private String createdBy;
	
    private String createdTime;
	
    private String updatedBy;
	
    private String updatedTime;
	
    private Integer version;

}

分页的方法;

public Page<TempInfoPageEntity  > pageInfo(SearchDTO searchDto){
		StringBuffer dataSql = new StringBuffer("SELECT tab1.id, tab1.dev_id, tab1.dev_name, tab1.dev_mode,tab1.created_by, tab1.created_time, tab1.updated_by, tab1.updated_time,tab1.version FROM temp_info tab1 LEFT JOIN temp_thm_info tab2 ON tab1.dev_id = tab2.dev_id WHERE 1=1 ");
		StringBuffer countSql = new StringBuffer("SELECT count(*) FROM temp_info tab1 LEFT JOIN temp_thm_info tab2 ON tab1.dev_id = tab2.dev_id WHERE 1=1 ");

		Map<String,Object> params = new HashMap<>();
        StringBuilder whereSql = new StringBuilder();
		if(StringUtils.isNotBlank(searchDto.getAlgName())){
			whereSql.append(" and tab2.alg_name = :alg_name ");
			params.put("alg_name",searchDto.getAlgName());
		}
		
		if(searchDto.getAuthStatus() != null && searchDto.getAuthStatus() > 0){
			whereSql.append(" and tab2.auth_status = :auth_status ");
			params.put("auth_status",searchDto.getAuthStatus());
		}

		if(StringUtils.isNotBlank(searchDto.getDevKeyword())){
			whereSql.append(" and( tab1.dev_name like :dev_name or dev_mode like :dev_mode )");
			params.put("dev_name","%"+searchDto.getDevKeyword()+"%");
			params.put("dev_mode","%"+searchDto.getDevKeyword()+"%");
		}
		String sql1 = dataSql.append(whereSql).append(" order by tab1.created_time desc ").toString();
		Query dataQuery = em.createNativeQuery(sql1,AuthDeviceInfoPageEntity.class);
		Query countQuery = em.createNativeQuery(countSql.append(whereSql).toString());
		
		setParameters(countQuery,params);
		BigDecimal totalSize = new BigDecimal(countQuery.getSingleResult().toString());
		
		int start = (searchDto.getPageNo()-1)*searchDto.getPageSize();
		setParameters(dataQuery,params);
		dataQuery.setFirstResult(start);
    	dataQuery.setMaxResults(searchDto.getPageSize());
        List<AuthDeviceInfoPageEntity> data = dataQuery.setFirstResult(start).setMaxResults(searchDto.getPageSize()).getResultList();
        
        Pageable pageable = new PageRequest(searchDto.getPageNo()-1, searchDto.getPageSize());
        Page<TempInfoPageEntity> page = new PageImpl<TempInfoPageEntity>(data, pageable, totalSize.longValue());
        return page;
	}

 

 

不足之处,请指教……

您好!关于Spring Data JPA分页查询,您可以按照以下步骤进行操作: 1. 首先,确保您的项目中已经引入了Spring Data JPA依赖,以及相关的数据库驱动依赖。 2. 创建一个继承自JpaRepository的接口,用于定义您的数据访问操作。例如: ```java import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { // 在这里可以定义各种自定义的查询方法 } ``` 3. 在您的Service层或者Controller层注入该Repository,并使用其提供的分页方法进行查询。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public Page<User> getUsersByPage(int pageNum, int pageSize) { PageRequest pageRequest = PageRequest.of(pageNum, pageSize); return userRepository.findAll(pageRequest); } } ``` 在上述示例中,我们通过调用`userRepository.findAll(pageRequest)`方法实现了分页查询,并传入`PageRequest`对象来指定页码和每页大小。 4. 最后,在您的Controller层中使用该Service方法来处理分页查询请求,并将结果返回给前端。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public Page<User> getUsersByPage(@RequestParam int pageNum, @RequestParam int pageSize) { return userService.getUsersByPage(pageNum, pageSize); } } ``` 在上述示例中,我们通过`@RequestParam`注解来接收前端传递的pageNum和pageSize参数,并调用UserService中的方法进行查询。 这样,您就可以使用Spring Data JPA进行分页查询了。希望能对您有所帮助!如果您还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值