我有兩個物體,它們通過 OnetoOne 映射連接我只想保存一個物體資料并獲取另一個物體的資料并將其主鍵存盤在我們的表中我該怎么做請幫忙?
@Entity
class Vehicle
{
@Id
@GeneratedValue(statergy=GenerationType.IDENTITY)
private int id;
@OneToOne
@JoinColumn(name="device_id",referencedColumnName = "id")
private Device vehicleId;
}
uj5u.com熱心網友回復:
如果你的意思是你想在資料庫中保存一個 Vehicle 并且外鍵不為空(意味著你想保存在 DB 中的 Vehicle,將有一個設備映射到它),你可以通過:在資料庫,然后創建一個新的 Vehicle 物件(將 id 保留為 null,bcs 將它保存在資料庫中時會自動生成)。之后只需使用設定器將設備設定到車輛中。(例如:Vehicle.setDevice ( theDeviceObjecYouGotFromTheDatabase ))。
實作它的一種方法是: 注意:建議使用 VehicleDTO,但我對其進行了簡化。我還為物件使用了一些奇怪的名稱,只是為了更清楚。
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;
}
我假設我們在服務層,并且您已經創建了 VehicleRepository 和 DeviceRepository。
希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/391918.html
上一篇:@Transactional方法可以在不掛起的情況下呼叫另一個@Transactional方法嗎?
下一篇:如何降級節點版本?
