java—只更新实体,不在SpringBoot项目的数据库中插入新记录

oogrdqng  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(213)

我有一个方法,每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);
    }

}
l7mqbcuq

l7mqbcuq1#

如果要手动分配实体id,就像在 fetchConfirmedData() 方法,您应该尝试删除 @GeneratedValue(strategy = GenerationType.IDENTITY) 注解自 ApplicationEntity.id .

gg58donl

gg58donl2#

我猜你用错误的方式在id上使用注解。我是说,你为什么要定义 @Column(unique = true) 当一个id总是唯一的时候。
因此,请尝试删除该行,或将其更改为:

@Column(name = "name_of_id_column_in_your_db")

让我们知道它是否有效!

相关问题