1. 程式人生 > 其它 >JPA findAll分頁查詢連表查詢

JPA findAll分頁查詢連表查詢

技術標籤:JPA資料庫jpaspringmysql

實體類TaskWorkEntity

@Entity
@Data
@Accessors(chain = true)
@Table(name = "task_work")
public class TaskWorkEntity extends BaseEntity {

    private Long id;
	
	// EcTaskEntity 關聯關係 唯一欄位
    private String ecTaskSerial;

    private String taskWorkName;

    /**
     * 當使用JPA配置實體時,如果有兩個屬性(一個是一般屬性,一個是多對一的屬性)對映到資料庫的同一列,就會報錯。
     * 這時,在多對一的@JoinColumn註解中新增insertable = false, updatable = false就能解決。
     */
@ManyToOne @JoinColumn(name = "ecTaskSerial", insertable = false, updatable = false) private EcTaskEntity ecTaskEntity; }

實體類EcTaskEntity

@Entity
@Data
@Accessors(chain = true)
@Table(name = "ec_task")
public class EcTaskEntity extends BaseEntity {

    private
String serial; private String ecTaskName; }

關聯關係EcTaskEntity一對多TaskWorkEntity

下面是分頁查詢

		import org.springframework.data.domain.Page;
		import org.springframework.data.domain.PageRequest;
		import org.springframework.data.domain.Pageable;
		import org.springframework.data.domain.Sort;

		Page<
TaskWorkEntity>
page; Sort sort = Sort.by(Sort.Direction.DESC, "createTime"); Pageable pageable = PageRequest.of(currentPage , pageSize, sort); PageResultModel pageModel = new PageResultModel(); try { page = taskWorkRepository.findAll((root, query, cb) -> { List<Predicate> predicates = new ArrayList(); if (StringUtils.isNotBlank(status)) { Join<EcTaskEntity, TaskWorkEntity> join = root.join("ecTaskEntity", JoinType.LEFT); predicates.add(cb.equal(join.get("status"), status)); } if (StringUtils.isNotBlank(serial)) { predicates.add(cb.like(root.get("serial"), "%" + serial + "%")); } predicates.add(cb.equal(root.get("isDelete"), 0)); Predicate[] arrayPredicates = new Predicate[predicates.size()]; return cb.and(predicates.toArray(arrayPredicates)); }, pageable); } catch (Exception e) { }