spring boot data jpa-如何获取特定id的数据

hk8txs48  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(336)

我有两张table Ticket 以及 Flight . 一个航班可能有很多票。
我要给你看田野 departure_date , destination_date 从table上 Flight 以及 name , surname 从table上 Ticket . 只显示特定的数据 flight_id . 我使用findby方法。

实体飞行

@Entity
@Table(name = "flight")
public class Flight {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer flight_id;

@Column(name = "departureDate")
private Date departureDate;

@Column(name = "destinationDate")
private Date destinationDate;

@OneToMany(mappedBy = "flight")
@JsonManagedReference("flight")
private List<Ticket> tickets;

实体票证

@Entity
@Table(name = "ticket")
public class Ticket {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int ticket_id;

@Column(name = "name")
private String name;

@Column(name = "surname")
private String surname;

@ManyToOne(targetEntity = Flight.class)
@JoinColumn(name = "flight_id")
@JsonBackReference("flight")
@Fetch(FetchMode.JOIN)
private Flight flight;

我创建了文件flightstickedto,其中包含某些字段:

public class FlightTicketDto {

private Integer flight_id;
private Date departureDate;
private Date destinationDate;
private String name;
private String surname;

public FlightTicketDto() {
}

public FlightTicketDto(Integer flight_id, Date departureDate, Date destinationDate, String name, String surname) {
    this.flight_id = flight_id;
    this.departureDate = departureDate;
    this.destinationDate = destinationDate;
    this.name = name;
    this.surname = surname;
}

flightticketrepository与我的查询

public interface FlightTicketRepository extends JpaRepository<Ticket, Integer> {

 @Query("SELECT new pl.edu.wat.dto.FlightTicketDto(f.flight_id, f.departureDate, f.destinationDate, t.name, t.surname) "
        + "FROM Flight f INNER JOIN f.tickets t")
 List<FlightTicketDto> findByFlightId(Integer flight_id);
 }

flightticketcontroller

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
public class FlightTicketController {

@Autowired
FlightTicketRepository flightTicketRepository;

@GetMapping("/mytickets/{flight_id}")
public List fetchEmpDeptDataInnerJoin(@PathVariable Integer flight_id) {
    return flightTicketRepository.findByFlightId(flight_id);
}

不管怎样 flight_id (甚至不是航班号,只是另一个号码)我写着,我有我所有的 flights 例如,我只想得到 flight_id = 431 ,结果可以在图片上看到。怎么了?

bzzcjhmw

bzzcjhmw1#

替换

@Query("SELECT new pl.edu.wat.dto.FlightTicketDto(f.flight_id, f.departureDate, f.destinationDate, t.name, t.surname) "
        + "FROM Flight f INNER JOIN f.tickets t")
 List<FlightTicketDto> findByFlightId(Integer flight_id);

具有

@Query("SELECT new pl.edu.wat.dto.FlightTicketDto(f.flight_id, f.departureDate, f.destinationDate, t.name, t.surname) "
            + "FROM Flight f INNER JOIN f.tickets t where f.flight_id = :flight_id")
     List<FlightTicketDto> findByFlightId(@Param("flight_id") Integer flight_id);

相关问题