All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.hiboot.mcn.autoconfigure.jpa.predicate.FieldLikePredicate Maven / Gradle / Ivy

package cn.hiboot.mcn.autoconfigure.jpa.predicate;

import cn.hiboot.mcn.autoconfigure.jpa.AbstractPredicateProvider;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.util.StringUtils;

/**
 * FieldLikePredicate
 *
 * @author DingHao
 * @since 2022/1/22 16:11
 */
public class FieldLikePredicate extends AbstractPredicateProvider {

    private static final String LIKE = "%";
    private final String value;

    private boolean isNot;
    private boolean prefix;
    private boolean suffix;

    public FieldLikePredicate(String fieldName, String value) {
        super(fieldName);
        this.value = value;
    }

    @Override
    public boolean isValid() {
        return StringUtils.hasText(value);
    }

    @Override
    public Predicate doGetPredicate(Root root, CriteriaBuilder criteriaBuilder) {
        String pattern;
        if(prefix){
            pattern = LIKE + value;
        }else if(suffix){
            pattern = value + LIKE;
        }else {
            pattern = LIKE + value + LIKE;
        }
        Expression as = root.get(getFieldName()).as(String.class);
        return isNot ? criteriaBuilder.notLike(as,pattern):criteriaBuilder.like(as,pattern);
    }

    public FieldLikePredicate not(){
        this.isNot = true;
        return this;
    }

    private FieldLikePredicate prefix(){
        this.prefix = true;
        return this;
    }

    private FieldLikePredicate suffix(){
        this.suffix = true;
        return this;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy