繁体   English   中英

在调用外部API的Spring Boot实体中填充JPA

[英]Populate JPA in Spring Boot entities calling to an external API

可以在Spring Boot中使用JPA实体填充数据库来调用外部api吗? 如果我有一个称为Quote的实体:

package guru.springframework.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;

@Entity
public class Quote {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long _id;
    private String description;

    public Long getId() {
        return _id;
    }

    public void setId(Long id) {
        this._id = id;
    }

    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

}

如何在Spring Boot中调用此API https://quotesondesign.com/api-v4-0/填充数据库?

首先,我不知道代码的全局结构,但我想:

配置类别:

@Configuration
public class appConfig{
  @Bean
  RestTemplate restTemplate(){
    return new RestTemplate();
  }

  @Bean
  ObjectMapper objectMapper(){
    return new ObjectMapper();
  }
}

服务等级:

import guru.springframework.domain.Qoate;
// Other imports

@Service
public class service{

@Autowired
private RestTemplate restTemplate;


@Autowired
private ObjectMapper objectMapper;

@Autowired
private QuoteRepository quoteRepository;

public void populateQoats {
// You can chose one of these tow cases

// Case 1
ResponseEntity<List<Qoate>> response = restTemplate.exchange(
  "http://rest to get the list of Qoates",
  HttpMethod.GET,
  null,
  new ParameterizedTypeReference<List<Qoate>>(){});
List<Qoate> result = response.getBody();

// Case 1
String response = restTemplate.getForObject(
  "http://rest to get the list of Qoates",
  String.class);

  List<Qoate> result = objectMapper.readValue(response, new TypeReference<List<Qoate>>(){});

  // Save the list into a database
  if(Objects.nonNull(result)) result.stream().filter(Objects::nonNull).foreach(element -> quoteRepository.saveAndFlush(element));

}

}

仓库:

public interface QuoteRepository  extends JpaRepository<Quote,Long>{

}

有关信息:

从5.0版本开始,非阻塞式,反应式org.springframework.web.reactive.client.WebClient提供了RestTemplate的现代替代方案,并有效支持同步和异步以及流方案。 RestTemplate将在将来的版本中弃用,并且以后将不会添加主要的新功能。

更多细节

您可能需要添加到appConfig.classmainClass

@EntityScan("paackage of your entity class")
@ComponentScan({"package of you service class","package of you controller class if you have it"})
@EnableJpaRepositories("package of your repository clas")

最后,我希望这能解决您的需求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM