JPA中自定义查询语句

JPA中自定义查询语句

    • maven 依赖
    • 使用JpaRepository和JpaSpecificationExecutor提供的接口方法
    • 使用JpaRepository和JpaSpecificationExecutor并扩展自定义SQL
    • 使用JpaRepository和JpaSpecificationExecutor并扩展自定拼接SQL

maven 依赖

 <parent>
  <groupId>org.springframework.bootgroupId>
  <artifactId>spring-boot-starter-parentartifactId>
  <version>2.0.4.RELEASEversion>
  <relativePath>relativePath>
 parent>
 ......

使用JpaRepository和JpaSpecificationExecutor提供的接口方法

  1. 实体类
@Entity
@Table(name = "sensitive")
@ApiModel(value = "词汇信息")
public class Sensitive {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @javax.persistence.Column(name = "id", nullable = false, unique = true)
  private Long id;

  @NotNull
  @javax.persistence.Column(name = "type", nullable = false)
  private String type;

  @NotNull
  @javax.persistence.Column(name = "word", nullable = false)
  private String word;

  @javax.persistence.Column(name = "adduserid", nullable = false)
  private Long adduserid;

  @javax.persistence.Column(name = "addusername", nullable = false)
  private String addusername;

  @javax.persistence.Column(name = "addtime", nullable = false)
  private Long addtime = System.currentTimeMillis();
  ......
}
  1. Dao接口
@Repository
@Transactional
public interface SensitiveDAO extends JpaRepository<Sensitive, Long>, JpaSpecificationExecutor<Sensitive> {}
  1. 简单使用
@Lazy
@Service
public class SensitiveService {
  @Autowired
  private SensitiveDAO ensitiveDao;
  public Result<List<Sensitive>> selectSensitive() {
    try {
      List<Sensitive> result = ensitiveDao.findAll();
      if (0 < result.size()) return new Result<>(ResultStatus.SUCCESS_SELECT, result.size(), result);
      else return new Result<>(ResultStatus.NULL_SELECT);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new Result<>(ResultStatus.ERROR_SELECT_OUT);
  }
  ......
}

使用JpaRepository和JpaSpecificationExecutor并扩展自定义SQL

  1. Dao接口
@Repository
@Transactional
public interface SensitiveDAO extends JpaRepository<Sensitive, Long>, JpaSpecificationExecutor<Sensitive> {
  List<Sensitive> findByWord(String word);
  List<Sensitive> findByWordLike(String word);
  Page<Sensitive> findByWord(String word, Pageable pageable);
  Page<Sensitive> findByWordLike(String word, Pageable pageable);
  ......
}
  1. 简单使用
  ......
  public Result<List<Sensitive>> selectSensitive(String word) {
    try {
      List<Sensitive> result = ensitiveDao.findByWord(word);
      if (0 < result.size()) return new Result<>(ResultStatus.SUCCESS_SELECT, result.size(), result);
      else return new Result<>(ResultStatus.NULL_SELECT);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new Result<>(ResultStatus.ERROR_SELECT_OUT);
  }
  ......

使用JpaRepository和JpaSpecificationExecutor并扩展自定拼接SQL

  1. Dao接口
  // 拼接SQL在Service层实现
  1. 简单使用
  ......
  /**
   * 词汇查询.
   * @param type [选]词汇类型(精确)
   * @param word [选]词汇(模糊)
   * @param start [选]开始时间戳(毫秒级)
   * @param end [选]结束时间戳(毫秒级)
   * @param page [选必]当前页位置,从0计数
   * @param size [选]当前每页大小
   * @return
   */
  public Result<List<Sensitive>> selectSensitive(String type, String word, Long start, Long end, Integer page, Integer size) {
    try {
      Page<Sensitive> result = ensitiveDao.findAll(new Specification<Sensitive>() {
        private static final long serialVersionUID = -9055844959025246179L;
        @Override
        public Predicate toPredicate(Root<Sensitive> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
          List<Predicate> list = new ArrayList<Predicate>();
          Path<String> type = root.get("type");
          Path<String> word = root.get("word");
          Path<Long> date = root.get("addtime");
          // 精确条件
          if (null != sensitiveType && !"".equals(sensitiveType)) list.add(cb.equal(type, sensitiveType));
          // 模糊条件
          if (null != sensitive && !"".equals(sensitive)) list.add(cb.like(word, "%" + sensitive + "%"));
          // 范围条件
          if (start != null && end != null) list.add(cb.between(date, start, end));
          Predicate[] p = new Predicate[list.size()];
          return cb.and(list.toArray(p));
        }
      }, org.springframework.data.domain.PageRequest.of(page, size));
      return 0 == result.getTotalElements() ? new Result<>(ResultStatus.NULL_SELECT)
          : new Result<>(ResultStatus.SUCCESS_SELECT, page, size, result.getTotalElements(), result.getContent());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new Result<>(ResultStatus.ERROR_SELECT_OUT);
  }
  ......

你可能感兴趣的:(JPA)