使用JPA方法比较两个类属性

时间:2019-06-02 11:50:20

标签: java spring 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,但是遇到了同样的异常。正确的方法名称是什么?

1 个答案:

答案 0 :(得分:0)

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

那么您可以轻松使用:

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

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