java - 只需更新实体而不在 Spring Boot 项目中的数据库中插入新记录
问题描述
我有一种方法可以每 10 秒检查一次数据更改,并且我希望在检查数据是否更改后只是为了更新以前的数据,而不是在数据库中插入新记录。我的意思是每 10 秒将新记录插入到数据库中,最后,我的 API 如下所示:
[
{
"id": 1,
"provinceState": "Guadeloupe",
"countryRegion": "France",
"lat": "16.265",
"lon": "-61.551",
"latestTotalCases": 9302,
"diffFromPrevDay": 0
},
{
"id": 2,
"provinceState": "French Polynesia",
"countryRegion": "France",
"lat": "-17.6797",
"lon": "149.4068",
"latestTotalCases": 18263,
"diffFromPrevDay": 0
}
]
然后 10 秒后,我的 API 看起来像这样。
[
{
"id": 1,
"provinceState": "Guadeloupe",
"countryRegion": "France",
"lat": "16.265",
"lon": "-61.551",
"latestTotalCases": 9302,
"diffFromPrevDay": 0
},
{
"id": 2,
"provinceState": "French Polynesia",
"countryRegion": "France",
"lat": "-17.6797",
"lon": "149.4068",
"latestTotalCases": 18263,
"diffFromPrevDay": 0
},
{
"id": 3,
"provinceState": "Guadeloupe",
"countryRegion": "France",
"lat": "16.265",
"lon": "-61.551",
"latestTotalCases": 9302,
"diffFromPrevDay": 0
},
{
"id": 4,
"provinceState": "French Polynesia",
"countryRegion": "France",
"lat": "-17.6797",
"lon": "149.4068",
"latestTotalCases": 18263,
"diffFromPrevDay": 0
}
]
任何人都可以帮忙吗?
这是我的代码。
实体
@Entity
public class ApplicationEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true)
private Long id;
private String provinceState;
private String countryRegion;
private String lat;
private String lon;
private int latestTotalCases;
private int diffFromPrevDay;
public ApplicationEntity() {
}
public ApplicationEntity(Long id, String provinceState, String countryRegion, String lat, String lon, int latestTotalCases, int diffFromPrevDay) {
this.id = id;
this.provinceState = provinceState;
this.countryRegion = countryRegion;
this.lat = lat;
this.lon = lon;
this.latestTotalCases = latestTotalCases;
this.diffFromPrevDay = diffFromPrevDay;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getLatestTotalCases() {
return latestTotalCases;
}
public void setLatestTotalCases(int latestTotalCases) {
this.latestTotalCases = latestTotalCases;
}
public int getDiffFromPrevDay() {
return diffFromPrevDay;
}
public void setDiffFromPrevDay(int diffFromPrevDay) {
this.diffFromPrevDay = diffFromPrevDay;
}
public String getProvinceState() {
return provinceState;
}
public void setProvinceState(String provinceState) {
this.provinceState = provinceState;
}
public String getCountryRegion() {
return countryRegion;
}
public void setCountryRegion(String countryRegion) {
this.countryRegion = countryRegion;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
@Override
public String toString() {
return "ApplicationEntity{" +
", provinceState='" + provinceState + '\'' +
", countryRegion='" + countryRegion + '\'' +
", lat=" + lat +
", lon=" + lon +
'}';
}
}
存储库
public interface ApplicationRepository extends JpaRepository<ApplicationEntity, Long> {
Optional<ApplicationEntity> findEntityById(Long id);
}
服务
@Service
public class ApplicationService extends ServiceAbstractionLayer {
private final ApplicationRepository applicationRepository;
private List<ApplicationEntity> allStats = new ArrayList<>();
@Autowired
public ApplicationService(ApplicationRepository applicationRepository) {
this.applicationRepository = applicationRepository;
}
@Autowired
private EntityManagerFactory entityManagerFactory;
public void addEntity(ApplicationEntity entities) {
applicationRepository.save(entities);
}
public List<ApplicationEntity> getEntities() {
return applicationRepository.findAll();
}
public void deleteAll() {
applicationRepository.deleteAll();
}
public ApplicationEntity findEmployeeById(Long id) {
return applicationRepository.findEntityById(id).orElseThrow(() -> new ApiRequestException("Case by id " + id + " was not found!"));
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Scheduled(cron = "*/10 * * * * *")
@PostConstruct
@Override
public void fetchConfirmedData() throws IOException, InterruptedException {
List<ApplicationEntity> newStats = new ArrayList<>();
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(Constants.URL_CONFIRMED)).build();
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
StringReader csvBodyReader = new StringReader(httpResponse.body());
Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(csvBodyReader);
for (CSVRecord record : records) {
ApplicationEntity locationStats = new ApplicationEntity();
for (long j = 0; j <= newStats.size(); j++)
locationStats.setId(j);
locationStats.setProvinceState(record.get("Province/State"));
locationStats.setCountryRegion(record.get("Country/Region"));
locationStats.setLat(record.get("Lat"));
locationStats.setLon(record.get("Long"));
int latestCases = Integer.parseInt(record.get(record.size() - 1));
int prevDayCases = Integer.parseInt(record.get(record.size() - 2));
locationStats.setLatestTotalCases(latestCases);
locationStats.setDiffFromPrevDay(latestCases - prevDayCases);
newStats.add(locationStats);
addEntity(locationStats);
}
this.allStats = newStats;
}
public List<ApplicationEntity> getAllStats() {
return allStats;
}
@Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory);
}
控制器
@RestController
public class ApplicationController {
private final ApplicationService applicationService;
@Autowired
public ApplicationController(ApplicationService applicationService) {
this.applicationService = applicationService;
}
@GetMapping("/all")
public ResponseEntity<List<ApplicationEntity>> getAlldb() {
List<ApplicationEntity> allStats = applicationService.getEntities();
return new ResponseEntity<>(allStats, HttpStatus.OK);
}
@GetMapping("/all/{id}")
public ResponseEntity<ApplicationEntity> getEntityById(@PathVariable("id") Long id) {
ApplicationEntity entity = applicationService.findEmployeeById(id);
return new ResponseEntity<>(entity, HttpStatus.OK);
}
@DeleteMapping("/delete/all")
public ResponseEntity<?> deleteAllEntities() {
applicationService.deleteAll();
return new ResponseEntity<>(HttpStatus.OK);
}
}
主班
@EnableScheduling
@EnableTransactionManagement
@SpringBootApplication
public class Covid19RestApiApplication {
public static void main(String[] args) {
SpringApplication.run(Covid19RestApiApplication.class, args);
}
}
解决方案
如果您手动分配实体 ID,就像您在fetchConfirmedData()
方法中所做的那样,您应该尝试@GeneratedValue(strategy = GenerationType.IDENTITY)
从ApplicationEntity.id
.
推荐阅读
- python - 更改按钮按下 Tkinter 上的小部件(Python)
- java - java.net.URL/URI 认为无效的 URL 是有效的
- lua - Lua 如果 A==1 或 2 或 3 那么
- php - 在我现有的用户名 PHP(Codeigniter) 中添加前缀
- java - 为什么 Hibernate 在我的表上生成重复的主键
- c# - 需要局部变换,来自全局变换 (C#) Unity 3d
- python - 字符串不能通过 'PLUS' 扩展
- c# - 在 Visual Studio 2017 上通过 Selenium 执行 Nunit 测试时找不到类型或命名空间名称“IWebDriver”错误
- linux - Debian Gnu/Linux 中的 USB 串行写入和读取数据问题
- java - 如何在函数中包含代码