JPA自定義sql的三種方式


1:在repository接口上注解@Query參數

1:@Query("select o from  AgentInfo  o  where o.userId = ?1 and o.balance<0")
2:@Query(value = "SELECT * FROM fl_agentinfo a inner join(SELECT id FROM fl_agentinfo where user_id = ?1 and device_wxid = ?2 order by id desc limit ?3,15) b on a.id = b.id",nativeQuery = true)

    加上 nativeQuery = true 字段名稱就要對應數據庫,可以實現稍微復雜一些的連表查詢
    修改的話注意要加@Modifying 和 @Transactional注解

2.第二種 實現Specification可以用來做一些需要過濾條件的查詢

    agentInfoRepository.findAll(new Specification<AgentInfo>() {
                    @Override
                    public Predicate toPredicate(Root<AgentInfo> root,
                                                 CriteriaQuery<?> query, CriteriaBuilder builder) {
                        List<Predicate> predicates = new ArrayList<Predicate>();
                        predicates.add(builder.equal(root.get("userId"), userId));
                        if(StringUtils.isNotEmpty(deviceWxId)){
                            predicates.add(builder.equal(root.get("deviceWxId"), deviceWxId));
                        }
                        if(StringUtils.isNotEmpty(wxName)){
                            predicates.add(builder.equal(root.get("wxName"), wxName));
                        }
                        query.where(predicates.toArray(new Predicate[predicates.size()]));
                        return null;
                    }
                }, pageable);

 

 3.使用entityManager完全自定義的拼接sql

      StringBuilder datasql = new StringBuilder("SELECT * FROM fl_handlercash a inner join (select id from fl_handlercash where user_id ="+userId);
        StringBuilder countSql = new StringBuilder("select count(*) from fl_handlercash where user_id ="+userId);
        Date startTime = null;
        Date endTime = null;
        if (StringUtils.isNotEmpty(startTimeStr)) {
            startTime = new Date(NumberUtils.toLong(startTimeStr));
            endTime = new Date(NumberUtils.toLong(endTimeStr));
            datasql.append(" and createTime between '"+DateTimeUtil.dateToStr(startTime)+"' and '"+DateTimeUtil.dateToStr(endTime)+"'");
            countSql.append(" and createTime between '"+DateTimeUtil.dateToStr(startTime)+"' and '"+DateTimeUtil.dateToStr(endTime)+"'");
        }
        if (status != -1) {
            if (status == 0) {
                datasql.append(" and status = 0");
                countSql.append(" and status = 0");
            } else {
                datasql.append(" and status <> 0");
                countSql.append(" and status <> 0");
            }
        }
        if (StringUtils.isNotEmpty(wxId)) {
            datasql.append(" and cash_wxid ='"+ wxId+"'");
            countSql.append(" and cash_wxid ='"+ wxId+"'");
        }
        if (StringUtils.isNotEmpty(deviceWxId)) {
            datasql.append(" and device_wxId ='"+ deviceWxId+"'");
            countSql.append(" and device_wxId ='"+ deviceWxId+"'");
        }
        datasql.append(" order by id desc limit "+(page-1)*10+",10) b on a.id = b.id");
        List<HandlerCash> handlerCashes = entityManager.createNativeQuery(datasql.toString(),HandlerCash.class).getResultList();
        BigInteger count = (BigInteger)entityManager.createNativeQuery(countSql.toString()).getSingleResult();
        PageBean<HandlerCash> pageBean = new PageBean(page+1, count.intValue(), 0,handlerCashes);

本文是個人代碼總結,方便以后查找。如果各位有其他方式歡迎分享

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM