maven 依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId><version>2.3.12.RELEASE</version>
</dependency>
实体类
package cn.xxx.xxx.project.dal.mysql.dataobject;import lombok.Data;
import org.hibernate.annotations.GenericGenerator;import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "abtest_normal")
@Data
public class AbtestNormalDO {@Id@GeneratedValue(generator = "custom_id")@GenericGenerator(name = "custom_id", strategy = "cn.yizhoucp.cupid.project.dal.mysql.strategy.CustomIdGenerator")private Long id;private String name;private String description;private String config;private Date created_at;private Date updated_at;private Date deleted_at;private Integer status;private String vest_channel;private String experiment_id;private String creator;private String solidify_abtest;
}
DAO
package cn.xxx.xxx.project.dal.mysql.dao;import cn.xxx.xxx.project.dal.mysql.dataobject.AbtestNormalDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;import javax.transaction.Transactional;
public interface AbtestNormalDAO extends JpaSpecificationExecutor<AbtestNormalDO>, CrudRepository<AbtestNormalDO, Long> {}
动态条件查询
import org.springframework.data.jpa.domain.Specification; import javax.persistence.criteria.CriteriaBuilder;import javax.persistence.criteria.CriteriaQuery;import javax.persistence.criteria.Predicate;import javax.persistence.criteria.Root;private Specification<AbtestNormalDO> getAbtestNormalSpecification(String vest_channel, Integer status) {Specification<AbtestNormalDO> specification = new Specification<AbtestNormalDO>() {@Overridepublic Predicate toPredicate(Root<AbtestNormalDO> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {List<Predicate> predicates = new ArrayList<>();if (!StringUtils.isEmpty(vest_channel)) {predicates.add(criteriaBuilder.equal(root.get("vest_channel"), vest_channel)); }if (Objects.nonNull(status)) {predicates.add(criteriaBuilder.equal(root.get("status"), status)); }return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));}};return specification;}public List<AbtestNormalDO> abtestNormalFind(String vest_channel, Integer status) {log.info("入参 vest_channel : {} status : {}", vest_channel, status);if (StringUtils.isEmpty(vest_channel) || Objects.isNull(status)) {throw new ServiceException(ErrorCode.INVALID_PARAM);}Specification<AbtestNormalDO> spec = getAbtestNormalSpecification(vest_channel, status);List<AbtestNormalDO> all = abtestNormalDAO.findAll(spec);return all;}