darrachequesne / spring-data-jpa-datatables

Spring Data JPA extension to work with the great jQuery plugin DataTables (https://datatables.net/)
Apache License 2.0
440 stars 174 forks source link

Show ManyToMany data #154

Closed dima-bzz closed 3 months ago

dima-bzz commented 7 months ago

Hi, I have two objects, a transport and a driver. How do I get all the transport in the driver and get the drivers in the transport. At the same time, do not use each other's services.

public class Driver {
     ...
     @ManyToMany(fetch = LAZY)
     @JoinTable(name = "driver_transport"
          joinColumns = @JoinColumn(name = "driver_id", referencedColumnName = "id"),
          inverseJoinColumns = @JoinColumn(name = "transport_id", referencedColumnName = "id")
     )
     private Set<Transport> transports = new HashSet<>();
     ...
}

public class Transport {
     ...
     @ManyToMany(fetch = LAZY, mappedBy = "transports")
     private Set<Driver> drivers = new HashSet<>();
     ...
}

public class DriverService {
     ...
     public class DataTablesOutput<DriverResponse> list(DataTablesInput input) {
          Function<Driver, DriverResponse> apply = driver -> modelMapper.map(driver, DriverResponse.class);

          return driverRepository.findAll(input, null, null, apply); 
     }

     public class DataTablesOutput<TransportResponse> listTransports(DataTablesInput input) {
          ?????
     }
     ...
}

public class TransportService {
     ...
     public class DataTablesOutput<TransportResponse> list(DataTablesInput input) {
          Function<Transport, TransportResponse> apply = transport -> modelMapper.map(transport, TransportResponse.class);

          return driverRepository.findAll(input, null, null, apply); 
     }

     public class DataTablesOutput<DriverResponse> listDrivers(DataTablesInput input) {
          ?????
     }
     ...
}
darrachequesne commented 3 months ago

For future readers:

I've added an example in the documentation: https://github.com/darrachequesne/spring-data-jpa-datatables/blob/main/README.md#handle-onetomany-and-manytomany-relationships

Please ping me if something is not clear enough.