How to filter by a column when it belongs to a composite primary key in Spring… here is a solution to the problem.
How to filter by a column when it belongs to a composite primary key in Spring
There is a DAO like this:
@Entity
@Table(name="booking")
public class BookingObject implements Serializable{
private static final long serialVersionUID = 1L;
@EmbeddedId
private CompositeId compositePK;
private LocalDate init_date;
private LocalDate end_date;
private int confirmation;
getters and setters
and composite primary keys:
@Embeddable
public class CompositeId implements Serializable{
private static final long serialVersionUID = 1L;
@NotNull
private String guest;
@NotNull
private String idhousing;
getters and setters
So I can now call
findById(new CompositeId(guest, idhousing)) from my @RestController;
。
The question is: what if I want to filter by one of the columns of the composite primary key, like guest.
I can’t do findByguest
because guest no longer exists in my DAO BookingObject
. So how can I get “Give me all guest equals… rows”
Solution
You can try findByExample
CompositeId compId= new CompositeId();
compId.setGuest(guestVal);
BookingObject bookingObj= new BookingObject ();
bookingObj.setCompositeId(compId);
Example<BookingObject> bookExample = Example.of(bookingObj);
List<BookingObject> objList=repository.findAll(bookExample);