我有两个实体,它们通过一对一映射连接 我只想保存一个实体数据并获取另一个实体和地图的现有 ID
I have two entity they are connected by one to one mapping i want to save only one entity data and get the existing id of another entity and map
我有两个实体,它们通过 OnetoOne 映射连接,我只想保存一个实体数据并获取另一个实体的数据并将其主键存储在我们的 table 我该怎么做,请帮忙?
@Entity
class Vehicle
{
@Id
@GeneratedValue(statergy=GenerationType.IDENTITY)
private int id;
@OneToOne
@JoinColumn(name="device_id",referencedColumnName = "id")
private Device deviceId;
}
如果你的意思是你想在数据库中保存一个车辆并且外键不为空(意味着你想保存在数据库中的车辆,将有一个设备映射到它),你可以通过:
在数据库中找到设备,然后创建一个新的 Vehicle 对象(将 id 保留为 null,因为它会在您将其保存在数据库中时自动生成)。
之后只需使用 setter 将设备设置到车辆中。
(例如: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;
}
假设我们在Service层,你已经创建了VehicleRepository & DeviceRepository
希望对您有所帮助。
我有两个实体,它们通过 OnetoOne 映射连接,我只想保存一个实体数据并获取另一个实体的数据并将其主键存储在我们的 table 我该怎么做,请帮忙?
@Entity
class Vehicle
{
@Id
@GeneratedValue(statergy=GenerationType.IDENTITY)
private int id;
@OneToOne
@JoinColumn(name="device_id",referencedColumnName = "id")
private Device deviceId;
}
如果你的意思是你想在数据库中保存一个车辆并且外键不为空(意味着你想保存在数据库中的车辆,将有一个设备映射到它),你可以通过: 在数据库中找到设备,然后创建一个新的 Vehicle 对象(将 id 保留为 null,因为它会在您将其保存在数据库中时自动生成)。 之后只需使用 setter 将设备设置到车辆中。 (例如: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;
}
假设我们在Service层,你已经创建了VehicleRepository & DeviceRepository
希望对您有所帮助。