How to create a get request for many-to-one columns?

Malik Safwan

I currently have made a spring boot project which is for an event system. In the model for booking class, I have two objects one is an event and the other one is the user. Now I want to create a get request that allows me to get all bookings made by a single user and all the bookings for a single event respectively. I have managed to create the other requests which are getting all the bookings and getting a booking by the booking id.

Right now if I try to make create any sort of implementation it either gives me a null pointer error or tells me the table relation "booking" doesn't exist. Please let me know if it's possible to write such a get request. Thanks

Model:

@Id
@SequenceGenerator(
        name = "booking_sequence",
        sequenceName = "booking_sequence",
        allocationSize = 1
)
@GeneratedValue(
        strategy = GenerationType.SEQUENCE,
        generator = "booking_sequence"
)
private Long id;

@ManyToOne
@JoinColumn(
        name = "event_id",
        referencedColumnName = "id"
)
private Event event;

@ManyToOne
@JoinColumn(
        name = "user_id",
        referencedColumnName = "id"
)
private User user;

private Integer tickets;
@Transient
private Integer amount;

Repository:

@Repository
public interface BookingRepository extends JpaRepository<Booking, Long > {
    @Query
    Optional<Booking> findBookingById(Long id);
}

Service:

@Autowired
public BookingService(BookingRepository bookingRepository) {
    this.bookingRepository = bookingRepository;
}

public List<Booking> getBookingList() {
    return bookingRepository.findAll();
}

public Booking getSingleBooking(Long bookingId) {
    return bookingRepository.findBookingById(bookingId).orElseThrow();
}

Controller:

@GetMapping
public List<Booking> getBookings() {
    return bookingService.getBookingList();
}

@GetMapping(path = "{bookingId}")
public Booking getSingleBooking(@PathVariable("bookingId") Long bookingId) {
    return bookingService.getSingleBooking(bookingId);}

@GetMapping(path = "/user/{userId}")
public List<Booking> getUserBookings(@PathVariable("userId") Long userId) {
    return bookingService.getBookingByUser(userId);}

@GetMapping(path = "/event/{eventId}")
public List<Booking> getEventBookings(@PathVariable("eventId") Long eventId) {
    return bookingService.getBookingForEvent(eventId);}
Malik Safwan

So it is possible to make such requests, all I did was use "nativeQuery" so that it would function the way I want it to. As mentioned I wanted to make two get-requests and here is how I wrote the queries for them.

Getting all user bookings of a specific user using its "ID":

@Query(value = "SELECT * from bookings, user where bookings.user_id = :id", nativeQuery = true)
List<Booking> findByUserid(Long id);

Getting all event bookings of a specific event using its "ID":

@Query(value = "SELECT * from bookings, user where bookings.event_id = :id", nativeQuery = true)
List<Booking> findByEventid(Long id);

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

How to split one dataframe column into many columns

How to create a one to many relationship using GraphQL?

One fetch request creates many GET requests on server

SQL create new column based on the one-to-one or one-to-many relationship between two original columns

how to create multiple objects with one request DRF

How to create One-to-Many and Many-to-One Relationship from one class to another class in Java/IntelliJ

how to cancel one of the pending http request from many angular 8

how to convert one string row into many columns in pandas?

How to concatenate many more columns to one column with list format?

How to separate one column into many columns in a .txt file?

In Pandas, how to create a unique ID based on the combination of many columns?

How to create HTTP GET request Scapy?

Many cases in one request in NSPredicate

Transform one to many data to columns

How To Create Flutter Moor Relationship With One-To-Many Join

How to create a query to match many items to one item

How to create one glacier archive for many s3 objects?

one hot encoding many columns of mixed data

Multiply many columns by one column in dask

How to get just one frequency of occurrence for items in different columns?

How do I get information in one column into 2 new columns?

SQL Server: How to customize one column in Order By clause out of many other columns in order by

How to efficiently reshape one column matrix to many specific length columns by moving specific interval

How Do I Get Sonarqube to Create Pull Request Comments

how to pivot when there are many columns

How to create for loop to create string search flag columns based on list of terms, then combine into one column

How to create a new request

How to create and save a one to many relationship (Parent Child) using a tableView and Realm

How to create one to many relationships in neo4j graph in most efficient way?

TOP lista

  1. 1

    Problema de escalada que requer programação dinâmica

  2. 2

    Argumento de linha de comando adicionando um parâmetro extra

  3. 3

    Como usar o foco no RichText no flutter?

  4. 4

    Como enviar e-mail para vários destinatários com python?

  5. 5

    AWS Glue Crawler creates a table for every file

  6. 6

    Adicionar campos de texto dinâmicos por meio da seleção suspensa de componentes?

  7. 7

    React: update state with form data onChange using the spread operator

  8. 8

    Como validar número de telefone na laravel?

  9. 9

    ¿Cómo obtener las fechas alternativas entre dos fechas en la misma tabla e insertar esas fechas en una tabla temporal?

  10. 10

    Usando Retrofit, quero acessar o userId a partir da resposta JSON (um valor de uma matriz dentro do objeto)

  11. 11

    UnsatisfiedDependencyException: Error creating bean with name 'securityConfig'

  12. 12

    Comportamento complexo do bootstrap Collapse

  13. 13

    Multilinha EditText com "botão de próxima visualização" em vez de "botão de nova linha"

  14. 14

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  15. 15

    Erro de "recurso de fonte não encontrado" do Android

  16. 16

    Aviso do ponto de interrupção do código do Visual Studio: o código-fonte é diferente da versão original

  17. 17

    O campo requer um bean do tipo que não pôde ser encontrado, considere definir um bean do tipo em sua configuração

  18. 18

    Como posso colar várias linhas do Excel para um DataGridView em C #?

  19. 19

    volatile for signal handler and multi-threading

  20. 20

    Javascript <input> não funciona bem com o IE 11

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo