I have two entity they are connected by OnetoOne mapping i want to save only one entity data and get the data of another entity and store its primary key in our table how can i do please help?
@Entity
class Vehicle
{
@Id
@GeneratedValue(statergy=GenerationType.IDENTITY)
private int id;
@OneToOne
@JoinColumn(name="device_id",referencedColumnName = "id")
private Device vehicleId;
}
CodePudding user response:
If you mean you want to save a Vehicle in the database and have the Foreign Key be not null (meaning the Vehicle you want to save in DB, will have a Device mapped to it), you can do that by: finding the Device in the database, then create a new Vehicle object (leave id as null, bcs it will be auto generated when you save it in the db). After that just use a setter to set the Device into the Vehicle. (ex: vehicle.setDevice(theDeviceObjecYouGotFromTheDatabase)).
A way to implement it would be this: Note: A VehicleDTO would be recommended, but I simplified it. Also I used some weird names for the objects just to be more clear.
public Vehicle saveVehicle(Vehicle vehicleToBeSaved, Long deviceId) {
Device deviceThatWasInDb = this.deviceRepository.findById(deviceId)
.orElseThrow(() -> {
throw new EntityNotFoundException("Device with this id was not in the db");
});
// assuming that the vehicleToBeSaved has null id, you just need to use a setter to set the device field
vehicleToBeSaved.setDevice(deviceThatWasInDb);
Vehicle vehicleAfterBeingSaved = this.vehicleRepository.save(vehicleToBeSaved);
return vehicleAfterBeingSaved;
}
I assumed that we are in Service layer, and you already have created the VehicleRepository & DeviceRepository.
Hope this helps.