首页 > 解决方案 > 使用 JPA 方法比较两个类属性

问题描述

我想使用 JPA 方法约定比较两个属性。

这是我的课

@Entity
@Table(name = "aircrafts")
public class Aircrafts {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Size(max = 45)
    @Column(name = "number", length = 45)
    private String number;

    @Column(name = "capacity")
    private int capacity;

    @Column(name = "seats_taken")
    private int seatsTaken;
}

这是我要实现的方法:

public interface AircraftsRepository extends JpaRepository<Aircrafts, Long> {
    public List<Aircrafts> findBySeatsTakenLessThanCapacity();
}

但是我得到了这个例外:

PropertyReferenceException: No property lessThanCapacity found for type int! Traversed path: Aircrafts.seatsTaken.

我试过使用 int 和 Integer 但我得到了同样的例外。哪个是正确的方法名称?

标签: javaspringjpa

解决方案


我认为@benji2505,正确地提到数据模型混合了“应该”在不同表中的东西。通常人们会期待两张表:飞机,航班。

然后你可以很容易地使用:

List<Flight> flightsWithFreeSeats = aircraftRepository
.findAll()
.stream()
.map(aircraft ->
 flightRepository.findByAircraftAndSeatsTakenLessThen(aircraft, aircraft.getCapacity)
)
.collect(Collectors.toList)

对于当前模型,@JZ Nizet 可能已经在他的评论中发布了最佳答案。


推荐阅读