Jpa-запрос Spring rest возвращает нулевое значение - PullRequest
0 голосов
/ 08 марта 2020

Я создаю API отдыха на Jhipster, который должен возвращать детали биллера, используя ID категории в качестве параметра поиска. Вызов конечной точки категорий возвращает список категорий, но вызов конечной точки биллеров с использованием одного из идентификаторов категорий возвращает нулевой результат.

public interface ApplicationUrl {

String BILLERS = "/category/{categoryid}";

}

Это контроллер:

@RequestMapping(ApplicationUrl.BASE_CONTEXT_URL)
public class BillingGatewayController {


    @Autowired
    private BillingGatewayService billingGatewayService;

@GetMapping(ApplicationUrl.BILLERS)
    public BillersServiceResponse getAllBillersByCatId(@PathVariable Long categoryId) {
        BillersServiceResponse defaultServiceResponse = new BillersServiceResponse();
        defaultServiceResponse.setMessage(Message.fail.name());
        ResponseCode responseCode = ResponseCode.BILLER_NOT_AVAILABLE;
        log.debug("REST request to get all billers");
        List<BillerDto> billers = billingGatewayService.findBillers(categoryId);
       if (CollectionUtils.size(billers) > 0) {
            responseCode = ResponseCode.SUCCESSFUL;
            defaultServiceResponse.setStatus(responseCode.getCode());
            defaultServiceResponse.setMessage(Message.SUCCESSFUL.name());
            defaultServiceResponse.setData(billers);
        }
        defaultServiceResponse.setStatus(responseCode.getCode());
        return defaultServiceResponse;
    }
}

Это классы обслуживания:

public interface BillingGatewayService {
List<BillerDto> findBillers(Long id);

}
public interface BillersRepository extends JpaRepository<Billers, Long>, JpaSpecificationExecutor<Billers> {

}

@Service("billingGatewayService")
public class BillingGatewayServiceImpl implements BillingGatewayService {

@Autowired
    private ExtBillersRepository billersRepository;

@Override
    public List<BillerDto> findBillers(Long categoryId) {
        BillerResponseDto billerResponseDto = new BillerResponseDto();
        List<BillerDto> billers = billersRepository.findAllActiveBillers(categoryId);
        billerResponseDto.setBillers(billers);
        billerResponseDto.setCategoryId(String.valueOf(categoryId));
        return billers;
      }
}
import com.fms.payfuze.dto.BillerDto;
import com.fms.payfuze.repository.BillersRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;


public interface ExtBillersRepository extends BillersRepository {

    String ACTIVE_BILLERS = "select new com.fms.payfuze.dto.BillerDto(b.id, b.name) from Billers b inner join b.categories c where c.id=b.id order by b.name";

    @Query(ACTIVE_BILLERS)
    List<BillerDto> findAllActiveBillers(@Param("id") Long id);
}

Это billerDTO:

public class BillerDto {

    private String billerId;

    private String nameOfBiller;

    public BillerDto(Long id, String name) {

        this.billerId = String.valueOf(id);
        this.nameOfBiller = name;
    }

    public String getBillerId() {
        return billerId;
    }

    public void setBillerId(String billerId) {
        this.billerId = billerId;
    }

    public String getNameOfBiller() {
        return nameOfBiller;
    }

    public void setNameOfBiller(String nameOfBiller) {
        this.nameOfBiller = nameOfBiller;
    }


}

и это класс Billers:

@Entity
@Table(name = "billers")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Billers implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "active")
    private Boolean active;

    @Column(name = "date_created")
    private Instant dateCreated;

    @OneToOne
    @JoinColumn(unique = true)
    private BillersRouterConfig billersRouterConfig;

    @OneToMany(mappedBy = "billers")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<TransactionDetails> billers = new HashSet<>();

    @ManyToMany(mappedBy = "billers")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JsonIgnore
    private Set<Categories> categories = new HashSet<>();


Getters and setters 


Я был на нем в течение нескольких дней и мозговой штурм, я буду признателен за все входные данные, но конструктивный и реконструктивный. Спасибо

Ответы [ 2 ]

2 голосов
/ 09 марта 2020

Вы передаете @Param("id") в свой репозиторий, но на самом деле вы не используете этот идентификатор в своем SQL Запросе. Ваше условие where имеет только оператор соединения. Вам нужно добавить AND c.id = :id после присоединения к таблице, чтобы вы могли указать, какую категорию вы хотите получить, по идентификатору категории.

Кроме того, в вашем выражении JOIN должно быть WHERE c.biller_id = b.id?

0 голосов
/ 12 марта 2020

Попробуйте что-то вроде этого

String ACTIVE_BILLERS = 
"select new com.fms.payfuze.dto.BillerDto(b.id, b.name)
 from Billers b inner join 
 b.categories c 
 where c.billers_id = b.id and c.billers_id = :id
 order by b.name";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...