jpa多条件查询重写Specification的toPredicate方法例子

1. Question对象

@Entity
@Table(name = "course_test_question")
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@EntityListeners(AuditingEntityListener.class)
public class Question extends BaseEntity {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="question_bank_id")
    @JsonIgnore
    @Where(clause = "status=1")
    QuestionBank questionBank;

    /**
     * 试题类型 对应QuestionTypeEnum
     */
    Byte questionType;

    /**
     * 试题状态 对应QuestionTypeEnum
     */
    Byte questionStatus;

    /**
     * 题干
     */
    @Column(columnDefinition="varchar(1024) DEFAULT NULL COMMENT '题干'")
    String questionName;

    @OneToMany(mappedBy = "question",fetch = FetchType.LAZY)
    @JsonIgnore
    @OrderBy("name ASC")
    @Where(clause = "status=1")
    List

2. 重写toPredicate例子说明:

public Page getListByBankIdAndType(String questionName, String questionBankId, QuestionTypeEnum questionTypeEnum) {
	// 创建分页对象
	PageRequest page = PageSort.pageRequest();

	QuestionBank questionBank = StringUtils.isNotEmpty(questionBankId) ? questionBankService.getId(questionBankId) : null;

	Specification querySpecifi = new Specification() {
		@Override
		public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
			List predicates = new ArrayList<>();
			
			//1. 根据字段模糊匹配 属性为questionName 为 String
			predicates.add(cb.like(root.get("questionName").as(String.class), "%" + questionName + "%"));
			
			//2. 根据字段精确匹配 属性questionType 为Byte
			predicates.add(cb.equal(root.get("questionType").as(Byte.class), questionTypeEnum.getCode()));

			//3. 属性为对象,精确匹配对象 属性questionBAnk 为QuestinBank
			predicates.add(cb.equal(root.get("questionBank").as(QuestionBank.class), questionBank));

			//4. 属性为对象,精确匹配对象的某一个字段 属性为QuestionBank(对象,其有属性status byte类型)
			Join join=root.join("questionBank", JoinType.INNER);
			predicates.add(cb.equal(join.get("status").as(Byte.class), StatusEnum.OK.getCode()));
			
			//5. 属性为list,精确匹配list中对象某一个属性字段的值
			Join join = root.join("option");
			preList.add(cb.equal(join.get("name"), name));

			//6. in操作,某一个属性对象的局限查询 属性为area(对象)
			List areaList = areaService.finAllByPid(question.getArea().getId().toString());
			Join join = root.join("area", JoinType.INNER);
			CriteriaBuilder.In in = cb.in(join.get("id").as(String.class));
			for (Area area : areaList) {
				in.value(area.getId());
			}
			predicates.add(in);
			

			return cb.and(predicates.toArray(new Predicate[predicates.size()]));
		}
	};

	return questionRepository.findAll(querySpecifi, page);
}

 

你可能感兴趣的:(java,JPA,toPredicate,java)