更新Airplane时出现Cannot resolve method 'equals(long)'错误求助
问题:更新飞机信息时ID校验报错
Cannot resolve method 'equals(long)' 我正在为机场APP构建REST API,在更新与Airline存在多对一关系的Airplane时,尝试校验飞机关联的航空公司ID是否与请求传入的ID一致,但代码中的equals()方法报错,提示“Cannot resolve method 'equals(long)'”,找不到匹配的方法调用。
出错的updateAirplane方法代码
@Override public AirplaneDto updateAirplane(long airlineId, long airplaneId, AirplaneDto airplaneDto) { Airline airline = airlineRepository.findById(airlineId).orElseThrow( () -> new ResourceNotFoundException("Airline", "id", airlineId)); Airplane airplane = airplaneRepository.findById(airplaneId).orElseThrow( () -> new ResourceNotFoundException("Airplane", "id", id)); // 此处存在变量未定义错误:id应为airplaneId if(!airplane.getAirline().getId().equals(airline.getId())) { throw new AirportAPIException(HttpStatus.BAD_REQUEST, "Airplane does not belong to the Airline"); } return null; }
Airplane实体类
@Getter @Setter @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "airplane") public class Airplane { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String aircraftRegistration; private String model; private long capacity; private String code; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "airline_id", nullable = false) private Airline airline; }
Airline实体类
@Getter @Setter @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "Airline", uniqueConstraints = {@UniqueConstraint(columnNames = {"name"})}) public class Airline { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; private String headquarters; @OneToMany(mappedBy = "airline", cascade = CascadeType.ALL, orphanRemoval = true) private Set<Airplane> airplanes = new HashSet<>(); }
解决方案
1. 直接用==比较基本类型数值
实体类中的id是基本类型long,基本类型没有equals()方法,直接用==比较数值即可:
if (airplane.getAirline().getId() != airline.getId()) { throw new AirportAPIException(HttpStatus.BAD_REQUEST, "Airplane does not belong to the Airline"); }
2. 将ID类型改为包装类Long(推荐)
把Airplane和Airline中的private long id;改为private Long id;,这样ID就变成对象类型,可以正常调用equals()方法。这也是JPA最佳实践之一,适配数据库主键可能为null的场景。
额外修复
updateAirplane方法中存在编译错误:new ResourceNotFoundException("Airplane", "id", id)里的id变量未定义,需替换为传入的airplaneId:
Airplane airplane = airplaneRepository.findById(airplaneId).orElseThrow( () -> new ResourceNotFoundException("Airplane", "id", airplaneId));
内容的提问来源于stack exchange,提问作者Sokoya Nifemi
相关产品推荐
相关产品推荐

