2016-12-21 1 views
1

방금 ​​스프링 부트를 사용하기 시작했으며 RestTemplate을 사용하여 쿼리를 호출하고 그 결과를 반환하고 싶습니다.SpringBoot : RestTemplate을 사용하여 쿼리 호출

@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); 
} 
} 

속성은 다음과 같습니다 :이 RestController에 쿼리 "findByMatchingCriteria를"전화 드렸습니다

@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); 
} 

@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/{부동산 ID}을 테스트 할 때 "다음 오류가 발생합니다.

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: [email protected]; 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: [email protected]; line: 1, column: 1] 

RestTemplate을 사용하여 쿼리를 호출하려면 어떻게해야합니까? 아니면 더 좋은 방법이 있을까요?

+0

컨트롤러와 저장소가 같은 프로젝트에 있습니까? – Adam

+0

저장소를 엔드 포인트로 공개 했습니까? – Gregg

+0

@ Adam 그들은 같은 프로젝트에 있지만 다른 마이크로 서비스에 있습니다. – Milebza

답변

1

는 해결책을 온 내 문제 때문에.

@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의 메서드를 호출

는 ApplicantRepository의 쿼리를 호출하는 ApplicantController에서 REST 방식을 만들었습니다.

내가 원했던 것은 REST가 통신 할 수있는 두 가지 다른 서비스 (매칭과 신청자)였다.

고맙습니다. @Adam 귀하의 제안은 저를 도왔습니다.

1

컨트롤러에서 직접 리포지토리를 호출하려는 경우 RestTemplate으로 HTTP를 이동할 필요가 없습니다. 당신이 어떤 이유로 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()); 
    } 
} 

: 간단하게 방법을 컨트롤러로 저장소를 주입하고, 전화 Get list of JSON objects with Spring RestTemplate

+0

microservices를 사용하고 저장소가 다른 서비스에 있기 때문에 HTTP를 사용하여 쿼리를 호출하기로했습니다. 나는 그것을 모두 캡슐화하고 휴식으로 의사 소통하기를 원했습니다. – Milebza

관련 문제