SpringBoot:使用RestTemplate调用查询

时间:2016-12-21 18:37:36

标签: java list spring-boot resttemplate

我刚刚开始使用Spring Boot,我想使用RestTemplate来调用查询并返回其结果。

@Repository
public interface ApplicantRepository extends CrudRepository<Applicant, Integer> {

@Query("SELECT a FROM Applicant a WHERE a.propertyTypeId = :typeId" +
        " AND a.bedrooms = :bedrooms" +
        " AND a.budget = :price")
List<Applicant> findByMatchingCriteria(@Param("typeId")int typeId, @Param("bedrooms") int bedrooms,
                                      @Param("price") int price);
}

我在这个RestController中调用了“findByMatchingCriteria”查询:

@RestController
public class MatchingController {

private RestTemplate restTemplate = new RestTemplate();

@RequestMapping(method = GET, value = "matchingByProperty/{propertyId}")
public List matchingByProperty(@PathVariable int propertyId) {
    Property property = restTemplate.getForObject("http://localhost:8080/api/properties/" + propertyId, Property.class);

    return restTemplate.getForObject("http://localhost:8080/api/applicants/search/findByMatchingCriteria?typeId=" + property.getTypeId()
                                            + "&bedrooms=" + property.getBedrooms()
                                            + "&price=" + property.getPrice(), List.class);
}
}

该属性如下所示:

@Entity
public class Property {
private @Id @GeneratedValue int id;
private String fullAddress;
private int typeId;
private int subtypeId;
private int bedrooms;
private int price;

private Property() {}

public Property(String fullAddress, int typeId, int subtypeId, int bedrooms, int price) {
    this.fullAddress = fullAddress;
    this.typeId = typeId;
    this.subtypeId = subtypeId;
    this.bedrooms = bedrooms;
    this.price = price;
}
// getters and setters
}

当我测试“matchingByProperty / {propertyId}”url时,我收到以下错误:

exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP     message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@3bd79387; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@3bd79387; line: 1, column: 1]

如何使用RestTemplate调用查询?或者有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

如果您只想从控制器调用自己的存储库,则无需使用RestTemplate覆盖HTTP。只需将存储库注入控制器,然后调用方法:

@RestController
public class MatchingController {

  @Autowired
  private ApplicantRepository applicantRepository;

  @RequestMapping(method = GET, value = "matchingByProperty/{propertyId}")
  public List matchingByProperty(@PathVariable int propertyId) {
    // You probably should not be going over HTTP for this either
    // and autowiring a property repository.
    Property property = restTemplate.
      getForObject("http://localhost:8080/api/properties/" + propertyId, Property.class);

    return applicantRepository.findByMatchingCriteria(property.getTypeId(), property.getBedrooms(), property.getPrice());
  }
}

如果您因某些原因想要通过HTTP,可以使用此处的方法:Get list of JSON objects with Spring RestTemplate

答案 1 :(得分:1)

为我的问题找到了解决方案。

在ApplicantController中创建一个REST方法,该方法调用ApplicantRepository的查询:

@RequestMapping(method = POST, value = "/api/applicants/getMatchedApplicants")
public List getMatchedApplicants(@RequestBody HashMap property) {

    List<Applicant> applicants = applicantRepository.matchedApplicants((int) property.get("typeId"),
                                                                        (int) property.get("bedrooms"),
                                                                        (int) property.get("price"));

    return applicants == null ? new ArrayList() : applicants;
}

然后MatchingController通过REST调用ApplicantController中的方法。

这就是我想要的,两种不同的服务(匹配和申请人)通过REST进行通信。

谢谢你@Adam你的建议帮助了我。