gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:37 24 4
gpt4 key购买 nike

是否可以在 Spring Boot 中调用外部 api 用 JPA 实体填充数据库?如果我有一个名为 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;
}

}

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

最佳答案

首先,我不知道您代码的全局结构,但让我假设:

配置类:

@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 开始,非阻塞、响应式(Reactive) org.springframework.web.reactive.client.WebClient 提供了 RestTemplate 的现代替代方案,可有效支持同步和异步以及流场景。 RestTemplate 将在未来版本中弃用,并且今后不会添加主要新功能。

For more details

您可能需要添加到您的 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")

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

关于java - 在调用外部 API 的 Spring Boot 实体中填充 JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53788977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com