首页 > 解决方案 > 当我使用从 REST API 列表中删除时不兼容的类型

问题描述

我正在尝试使用 spring-boot REST Web 服务中的用户名删除列表。我的删除方法的代码块是,

@PostMapping("/delete/{username}")
public List<String> delete(@PathVariable("username") final String username) {

    List<Location> locations = locationsRepository.findByUserName(username);
    locationsRepository.delete(locations);
    return getLocationsByUserName(username);
}

和 LocationsRepository 如下,

import com.smartfarm.dbservice.model.Location;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface LocationsRepository extends JpaRepository<Location, Integer> {
    List<Location> findByUserName(String username);
}

当我编译这个程序时,我收到错误,

incompatible types: java.util.List<com.smartfarm.dbservice.model.Location> cannot be converted to com.smartfarm.dbservice.model.Location

对此有任何建议/解决方案吗?

标签: spring-bootweb-servicesrest

解决方案


首先,您应该使用@DeleteMapping而不是@PostMapping.

你需要使用deleteAll方法;delete用于删除单个实体。你可以在这里查看

此外,一个好的建议是将删除方法的返回类型设置为void. 当您的 delete 方法正在返回getLocationsByUserName时,我假设它返回具有相同用户名的位置作为结果,无论如何这将是 null,您可以将返回类型设置为void并跳过对 的方法调用getLocationsByUserName


推荐阅读