spring-boot - 当我使用从 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
对此有任何建议/解决方案吗?
解决方案
首先,您应该使用@DeleteMapping
而不是@PostMapping
.
你需要使用deleteAll
方法;delete
用于删除单个实体。你可以在这里查看。
此外,一个好的建议是将删除方法的返回类型设置为void
. 当您的 delete 方法正在返回getLocationsByUserName
时,我假设它返回具有相同用户名的位置作为结果,无论如何这将是 null,您可以将返回类型设置为void
并跳过对 的方法调用getLocationsByUserName
。
推荐阅读
- python - 如何在 pyqtgraph 中设置跟踪名称?
- javascript - 使用 JQuery 从具有 JSON 值的表中选择行
- entity-framework - 实体框架 6:延迟加载不起作用
- java - Spring Async 中断 JPA - 分离实体传递给持久化
- sql - 从存储过程插入返回记录 - SQL
- c# - Serilog 与 .net c# 类库的集成
- google-app-engine - 无法在 Google Cloud 上创建实例 - “区域...”没有足够的资源
- firebase - Firebase Web SDK createUserWithEmailAndPassword 在创建后未登录用户
- html - Slider 中的内容不适合移动设备
- html - 制作标题的完美方法