RestFulClient CRUDRepository实现

时间:2017-02-21 17:01:45

标签: spring-boot crud resttemplate

我正在使用SpringBoot编写Web服务客户端。如何在客户端内使用CRUDRepository?我必须将数据从Web服务保存到数据库表?如何获取客户端内BookRepository的句柄?

public interface BookRepository extends CrudRepository<BooksStage, Long> {}     

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Books[]> responseEntity = restTemplate.getForEntity("http://localhost:8080/booksList", Books[].class); 
Books[] books=responseEntity.getBody(); 
if(books!=null){
log.info("booksreceived -"+books.length);            
for (Books c : books){
//Insert into database
}
}

1 个答案:

答案 0 :(得分:0)

1)接口BookRepository应该用@Repository注释。您应该在Web Service客户端类中自动装配BookRepository接口。

2)RestTemplate必须在带有@Service注释的Web Service客户端类中

3)由于您的实体名称为BooksStage,因此您只应保存BooksStage类型的实体(而不是Books)。

@Repository    
    public interface BookRepository extends CrudRepository<BooksStage, Long> {

}


@Service
public class MyWebServiceClient{

    @Autowired
    private BookRepository bookRepo; 

    public boolean updateSomeBook() {

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<BooksStage[]> responseEntity =     
           restTemplate.getForEntity ("http://localhost:8080/booksList", Books[].class); 
        BooksStage[] books=responseEntity.getBody(); 
        if(books!=null){
        log.info("booksreceived -"+books.length);            

        for (BooksStage c : books){
               bookRepo.save(c);
        }
        return true;
    }  
}

@Entity
@Table(name = "books_stage")
public class BooksStage {

    @Id
    @Column(name = "ID")
    private long id;

    //other related fields 

}