从外部API调用JSON数据并输入MySQL数据库的过程涉及以下几个基础概念:
以下是一个简单的Java Spring Boot Web应用示例,展示如何从外部API调用JSON数据并输入MySQL数据库。
在pom.xml
中添加以下依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
在application.properties
中配置数据库连接:
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class DataEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String value;
// Getters and Setters
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface DataRepository extends JpaRepository<DataEntity, Long> {
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class DataService {
@Autowired
private DataRepository dataRepository;
public void fetchDataFromApi() {
RestTemplate restTemplate = new RestTemplate();
String apiUrl = "https://api.example.com/data";
DataResponse[] dataResponses = restTemplate.getForObject(apiUrl, DataResponse[].class);
for (DataResponse response : dataResponses) {
DataEntity entity = new DataEntity();
entity.setName(response.getName());
entity.setValue(response.getValue());
dataRepository.save(entity);
}
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DataController {
@Autowired
private DataService dataService;
@GetMapping("/fetch-data")
public String fetchData() {
dataService.fetchDataFromApi();
return "Data fetched successfully";
}
}
public class DataResponse {
private String name;
private String value;
// Getters and Setters
}
try-catch
块捕获异常并记录日志。希望以上信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云