Home > Enterprise >  How to create a Map in a Jpa Repository
How to create a Map in a Jpa Repository

Time:12-26

Hello everyone i want to create a HashMap/Map inside a JPA Repository but i dont know how.

@Repository
public interface CurrentDeployedReservations extends JpaRepository<Reservation, CustomTable>{
    //Map(CustomTable, Reservation) findMap()?
}

Thank you


@SuppressWarnings("serial")
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Reservation implements Serializable {
    
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private Boolean accepted;
    private Long t_ID;
    @OneToOne
    @JoinColumn(name = "user_id")
    @JsonManagedReference
    private User user;
    @OneToOne
    @JoinColumn(name = "table_id")
    @JsonBackReference
    private CustomTable table;
    private String time;
    private int numberOfPeople;
}

@SuppressWarnings("serial")
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CustomTable implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private Boolean busy;
    private Boolean full;
    @JsonIgnore
    @OneToMany(mappedBy = "table", orphanRemoval = true, fetch = FetchType.EAGER)
    @JsonManagedReference
    private List<Reservation> reservations;
    
    public void addReservation(Reservation r) {
        this.reservations.add(r);
        r.setTable(this);
    }
    public void removeReservation(Reservation r) {
        r.setTable(null);
        this.reservations.remove(r);
    }
}

Here are the models. Thank you for asking ........................ ......................... ............................... .................................... ........................................................ ..............................................................

CodePudding user response:

I think you mistunderstood JpaRepository, the usage is: JpaRepository<T,ID>. In your case that would mean:

@Repository
public interface CurrentDeployedReservations extends JpaRepository<Reservation, Long> {

}

You could then use JpaRepository#findAll to get all Reservations, but that would not be equal to your Map. I'm still unsure why you need a Map when you have this relationship, but the following would work (provided your CustomTable has a getter for the Reservation):

@Repository
public interface CustomTableRepository extends JpaRepository<CustomTable, Long> {
  public Map<CustomTable, List<Reservation>> getAll() {
    return findAll().stream()
             .collect(Collectors.toMap(c -> c, CustomTable::getReservations));
  }
}

Your @OneToOne relation on your Reservations customeTable field should be @ManyToOne.

  • Related