How can I avoid unnecessary queries to the DB? I have LoadEntity with two nested entity - CarrierEntity and DriverEntity. Java class:
@Entity
public class LoadEntity {
...
@ManyToOne
@JoinColumn(name="carrier_id", nullable=false)
private CarrierEntity carrierEntity;
@ManyToOne
@JoinColumn(name="driver_id", nullable=false)
private DriverEntity driverEntity;
}
But API send me carrierId and driverId. I make it:
DriverEntity driverEntity = driverService.getDriverEntityById(request.getDriverId());
loadEntity.setDriverEntity(driverEntity);
loadRepository.save(loadEntity);
How can I write only driverId with JPA?
CodePudding user response:
With Spring Data JPA you can always fall back on plain SQL. Of course, this will side step all the great/annoying logic JPA gives you. This means you won't get any events and the entities in memory might be out of sync with the database. For this reason you might also increase the version column, if you are using optimistic locking.
That said you could update a sing field like this:
interface LoadRepository extends CrudRepository<LoadEntity, Long> {
@Query(query="update load_entity set driver_id = :driverId where carrier_id=:carrier_id", nativeQuery=true)
@Modifying
void updateDriverId(Long carrierId, Long driverId);
}
If you just want to avoid the loading of the DriverEntity
you may also use JpaRepository.getById